gpt4 book ai didi

python - 使用 dryscrape 和 BeautifulSoup 进行网页抓取

转载 作者:行者123 更新时间:2023-11-28 21:43:41 29 4
gpt4 key购买 nike

我正在尝试从 Yahoo 抓取一些数据。我写了一个有效的脚本 - 有时。有时当我运行脚本时,我能够下载完整的页面 - 其他时候,页面只加载了部分 - 数据部分丢失。

更令人困惑的是,当我在浏览器中导航到该页面时,会显示整个页面。

这是我的代码的要点:

import dryscrape
from bs4 import BeautifulSoup

url = 'http://finance.yahoo.com/quote/SPY/options?p=SPY&straddle=false'

sess = dryscrape.Session()

sess.set_header('user-agent', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0')

sess.set_attribute('auto_load_images', False)
sess.set_timeout(360)

sess.visit(url)

soup = BeautifulSoup(sess.body(), 'lxml')

# Related to memory leak issue in webkit
sess.reset()

# Barfs (sometimes!) at the line below
sel_list = soup.find('select', class_='Fz(s)')

if sel_list is None or len(sel_list) == 0:
print('element not found on page!')

我附上了下面获取的页面的图像。这是通过网络浏览器在互联网上查看时的网页:

Page showing data

现在,这是我通过类似于上面显示的脚本下拉的页面 - 它没有数据!:

Page downloaded by scraping - no data!

谁能弄清楚为什么当我的脚本获取数据时元素有时会丢失?同样(更?)重要的是,我该如何解决这个问题?

最佳答案

在使用 BeautifulSoup 解析数据之前,您可能需要等待数据加载。在 dryscrape 中等待可以通过 wait_for() 函数完成:

sess.visit(url)

# waiting for the first data row in a table to be present
sess.wait_for(lambda: session.at_css("tr.data-row0"))

soup = BeautifulSoup(sess.body(), 'lxml')

或者,无中生有:它也可能是暂时的(网络?)问题,您可以通过循环刷新页面来解决它,直到您看到结果,大致如下:

from dryscrape.mixins import WaitTimeoutError 

ATTEMPTS_COUNT = 5
attempts = 0

while attempts <= ATTEMPTS_COUNT:
sess.visit(url)

try:
# waiting for the first data row in a table to be present
sess.wait_for(lambda: session.at_css("tr.data-row0"))
break
except WaitTimeoutError:
print("Data row has not appeared, retrying...")
attempts += 1

soup = BeautifulSoup(sess.body(), 'lxml')

关于python - 使用 dryscrape 和 BeautifulSoup 进行网页抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41860952/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com