美丽的汤没有占据整张桌子
我正在尝试编写一个程序,从雅虎财经的列表中获取股票代码。我已经尝试过 将 html5lib 更改为 lxml 和 html.parser。这些都不适合我。 该网站是: https://finance.yahoo.com/screener/unsaved/f491bcb6-de80-4813-b50e-d6dc8e2f5623?dependentField=sector&dependentValues=Consumer%20Cyclical
应该有 25 个结果,但如果您通过运行我们发现我们只得到了大约一半。 (13)
大家有什么解决办法吗?
import requests
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36', 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language' : 'en-US,en;q=0.5', 'DNT' : '1', # Do Not Track Request Header 'Connection' : 'close'
}
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/screener/unsaved/f491bcb6-de80-4813-b50e-d6dc8e2f5623?dependentField=sector&dependentValues=Consumer%20Cyclical'
page = requests.get(URL, headers=headers, timeout=5)
soup = BeautifulSoup(page.content, "html5lib")
results = soup.find(id="screener-results")
stock_ = results.find_all("tr", class_="simpTblRow Bgc($hoverBgColor):h BdB Bdbc($seperatorColor) Bdbc($tableBorderBlue):h H(32px) Bgc($lv2BgColor)")
x = 0
for stock_ in stock_:
x = x + 1
stock_symbol = stock_.find('a', class_='Fw(600) C($linkColor)')
print(str(stock_symbol.text.strip()) + '\n' + str(x))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有一个简单的解决办法。该表对每一行使用交替颜色,因此一行的颜色为
。
Bgc($lv2BgColor)
,下一行的颜色为Bgc($lv1BgColor)
。由于您只能得到带有Bgc($lv2BgColor)
的结果,因此您只能得到一半的结果。这是屏幕截图
在您的情况下,实际上不需要对类如此精确,只需使用
class_="simpTblRow"
即可获得所有结果。顺便说一句:还有一个 Yahoo Finance API,每天最多可免费处理 100 个请求,因此您也许能够使用它而不是从他们的网页上抓取。
There is an easy fix for this. The table is using alternating colors for each row so one row has the color
of the relevant HTML of the webpage.
Bgc($lv2BgColor)
and the next oneBgc($lv1BgColor)
. As you only get those withBgc($lv2BgColor)
you only get half of the results.Here a screenshot
In your case there is actually no need to be so precise with the class, just use
class_="simpTblRow"
and you should get all results.By the way: There also is a Yahoo Finance API which is free for up to 100 requests per day so you might be able to use that instead of web scraping the from their web page.