Hom*_*lli 2 python lxml beautifulsoup web-scraping dryscrape
我正在尝试从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!')
Run Code Online (Sandbox Code Playgroud)
我已附上以下页面的图像。这是通过Web浏览器在Internet上查看时的网页:
现在,这是我通过类似于上面显示的脚本下拉的页面-它没有数据!:
任何人都可以弄清楚为什么在我的脚本中获取数据时有时会丢失该元素的原因吗?同样(更多?)重要的是,我该如何解决?
您可能需要等待数据加载之后才能使用进行解析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')
Run Code Online (Sandbox Code Playgroud)
或者,在黑暗中开枪:这也可能是暂时性的(网络?)问题,您可以通过循环刷新页面直到看到结果来解决此问题,方法如下:
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')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2556 次 |
| 最近记录: |