【问题标题】:Python web crawler not printing the resultsPython网络爬虫不打印结果
【发布时间】:2020-07-21 08:11:14
【问题描述】:

它没有打印出任何结果并返回一个奇怪的错误,如图所示使用pycharm。

我写的代码:

import requests
from bs4 import BeautifulSoup

def webcrawler(max_pages,url):
    page = 1
    if page <= max_pages:
        webpage = (url) + str(page)
        source_code = requests.get(url)
        code_text = source_code.text
        soup_format = BeautifulSoup(code_text)
        for link in soup_format.findAll('a', {'class': 's-item__image-wrapper'}):
            href = str(url) + link.get('href')
            title = link.string
            print(href)
            print(title)
        page += 1

webcrawler(1, 'https://www.ebay.com/b/Cell-Phone-Accessories/9394/bn_320095?_pgn=')

【问题讨论】:

  • 请不要发布代码或错误的图像。见meta.stackoverflow.com/questions/285551/…
  • 警告说要使用解析器
  • 另外,你确定你要提取的数据不是JS加载的,并且已经存在于你的source_code中了吗?
  • 您是否要提取页面中产品的所有超链接?

标签: python web-crawler


【解决方案1】:

警告消息会准确告诉您如何阻止它被引发。您只需将解析器传递给您在第 10 行实例化的 BeautifulSoup,例如

soup_format = BeautifulSoup(code_text, features='html.parser')

但是,您的代码还有一些问题。原始帖子中代码的第 11 行:

        for link in soup_format.findAll('a', {'class': 's-item__image-wrapper'}):

将返回None,因为没有&lt;a&gt;s-item__image-wrapper 的标签 - 目标页面中具有该类的所有标签都是&lt;div&gt;s。

我在下面有一个建议,似乎可以捕捉到您想要抓取的内容。相反,它会遍历每个 &lt;div class="s-item__image"&gt;,这是您要打印的项目数据的包装类。然后它向下钻取到第一个子 &lt;a&gt; 标记以获取项目 href 并在项目描述的包装器中获取项目 imgalt 属性 - 已更改这些的打印顺序并添加了为了便于阅读,请在下面的示例中添加新行。

import requests
from bs4 import BeautifulSoup

def webcrawler(max_pages,url):
    page = 1
    if page <= max_pages:
        webpage = (url) + str(page)
        source_code = requests.get(url)
        code_text = source_code.text
        soup_format = BeautifulSoup(code_text, features='html.parser')
        for wrapper in soup_format.findAll('div', attrs={'class': 's-item__image'}):
            href = str(url) + wrapper.find('a').get('href')
            title = wrapper.find('img').get('alt')
            print(title)
            print(href)
            print()
        page += 1

webcrawler(1, 'https://www.ebay.com/b/Cell-Phone-Accessories/9394/bn_320095?_pgn=')

【讨论】:

  • 非常感谢!我实际上对编码完全陌生,您的解释出现在
  • @RashikRahmanIshmum 不用担心 :) 我建议您以后始终阅读任何警告、异常、错误消息,因为它们通常对调试您的代码非常有帮助 - 但是在逻辑中存在更深层次的问题在这种情况下,您的代码也是如此。祝您旅途愉快
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-12
  • 1970-01-01
  • 2020-10-14
  • 2013-10-15
相关资源
最近更新 更多