【问题标题】:Having trouble when webscraping return nothing网页抓取时遇到问题不返回任何内容
【发布时间】:2021-11-25 23:42:51
【问题描述】:

我正在构建一个真实状态的网络抓取工具,当 html 中不存在某个索引时我遇到了问题。

我该如何解决这个问题?有这个问题的代码是这样的

info_extra = container.find_all('div', class_="info-right text-xs-right")[0].text

我是网络抓取的新手,所以我有点迷路了。

谢谢!

【问题讨论】:

  • 由于您只需要第一项,因此请使用find 而不是find_all。如果没有找到,它只会将值留空。

标签: python html python-3.x web-scraping


【解决方案1】:

一种通用方法是在尝试访问索引之前检查长度。

divs = container.find_all('div', class_="info-right text-xs-right")
if len(divs) > 0:
   info_extra = divs[0].text
else:
   info_extra = None

您可以通过知道空列表是错误的来进一步简化这一点。

divs = container.find_all('div', class_="info-right text-xs-right")
if divs:
   info_extra = divs[0].text
else:
   info_extra = None

您可以使用海象运算符:= 进一步简化


if (divs := container.find_all('div', class_="info-right text-xs-right")):
   info_extra = divs[0].text
else:
   info_extra = None

或全部在一行中:

info_extra = divs[0].text if (divs := container.find_all('div', class_="info-right text-xs-right") else None

【讨论】:

  • 这帮了很大的忙,我的代码工作了!!!非常感谢!
【解决方案2】:

我也是网络抓取的新手,我的大部分问题是当我要求页面上不存在的元素时

您尝试过 Try/Except 块吗?

try:
    info_extra = container.find_all('div', class_="info-right text-xs-right")[0].text
except Exception as e:
    raise

https://docs.python.org/3/tutorial/errors.html

祝你好运

【讨论】:

  • 不要raise或者你的catch没用,留言知道有print('oops the result is empty')这样的错误。这样你的脚本就不会中断,但 raise 会中断它
【解决方案3】:

首先,在对数据进行任何操作之前,您应该始终检查数据。
现在,如果您的选择器在站点中只有一个结果

info_extra_element = container.select_one('div.info-right.text-xs-right'
        )

if info_extra_element:
    info_extra = info_extra_element.text
else:

    # On unexpected situation where selector couldn't be found
    # report it and do something to prevent your program from crashing.

    print("selector couldn't be found on the page")
    info_extra = ''

如果有与你的选择器匹配的元素列表

info_extra_elements = container.select('div.info-right.text-xs-right'
        ).text
info_extra_texts = []

for element in info_extra_elements:
    info_extra_texts.append(element.text)

附言。
基于this 的回答,当您想基于类进行过滤时,最好使用 CSS 选择器。
如果只想根据元素标签进行过滤,可以使用 find 方法。

【讨论】:

    猜你喜欢
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 2019-04-27
    • 2021-10-15
    • 2019-07-07
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多