python - Beautifulsoup find_all 没有找到全部

标签 python beautifulsoup web-crawler findall

我目前正在开发网络爬虫。我希望我的代码能够从我抓取的所有网址中获取文本。函数 getLinks() 找到我想要从中获取数据的链接并将它们放入数组中。该数组当前已填充 12 个链接,如下所示: 'http://www.computerstore.nl/product/142504/category-100852/wd-green-wd30ezrx-3-tb.html '

这是我的函数代码,它使用从 getLinks() 获得的 url 循环遍历数组,并从中获取数据。所以我遇到的问题是它有时返回文本 6 次,有时 8 或 10 次。但不是应有的 12 次。

def getSpecs(): 
    i = 0 
    while (i < len(clinks)):
        r = (requests.get(clinks[i]))
        s = (BeautifulSoup(r.content))
        for item in s.find_all("div", {"class" :"productSpecs roundedcorners"}):
            print item.find('h3')
        i = i + 1 

getLinks()
getSpecs()

我该如何解决这个问题?请帮忙。

提前致谢!

最佳答案

以下是经过多项修复的改进代码:

  • 使用requests.Session在整个脚本生命周期中维护
  • 使用urparse.urljoin()连接 URL 部分
  • 使用CSS selectors而不是 find_all()
  • 改进了在页面上查找产品的方式
  • 将基于索引的循环转换为列表项上的Pythonic循环

代码:

from urlparse import urljoin

from bs4 import BeautifulSoup
import requests

base_url = 'http://www.computerstore.nl'
curl = ["http://www.computerstore.nl/category/100852/interne-harde-schijven.html?6437=19598"]

session = requests.Session()
for url in curl:
    soup = BeautifulSoup(session.get(url).content)
    links = [urljoin(base_url, item['href']) for item in soup.select("div.product-list a.product-list-item--image-link")]

    for link in links:
        soup = BeautifulSoup(session.get(link).content)
        print soup.find('span', itemprop='name').get_text(strip=True)

它抓取每个产品链接,跟踪它并打印出产品标题(12 个产品):

WD Red WD20EFRX 2 TB
WD Red WD40EFRX 4 TB
WD Red WD30EFRX 3 TB
Seagate Barracuda ST1000DM003 1 TB
WD Red WD10EFRX 1 TB
Seagate Barracuda ST2000DM001 2 TB
Seagate Barracuda ST3000DM001 3 TB
WD Green WD20EZRX 2 TB
WD Red WD60EFRX 6 TB
WD Green WD40EZRX 4 TB
Seagate NAS HDD ST3000VN000 3 TB
WD Green WD30EZRX 3 TB

关于python - Beautifulsoup find_all 没有找到全部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27346976/

相关文章:

python - 将计算值传递给 Django 模板

Python HTML : Extract Parts of Text from html file

python - Scrapy 响应不完整

python - 如何使用Python解析网页[html]上的Java脚本包含[动态]?

python - 在 Windows 上将 cx_Freeze 安装到 python

python - Seaborn 热图 : Move colorbar on top of the plot

python - 为什么 from tkinter import * 不导入 Tkinter 的消息框?

Python - BeautifulSoup4 decompose() 不起作用

python-3.x - 使用 Python 进行网页抓取,需要登录才能查看输出

web-crawler - 提交的 URL 被 robots.txt 阻止