gpt4 book ai didi

python - Beautiful Soup 无法从表中获取信息

转载 作者:太空宇宙 更新时间:2023-11-04 05:14:10 25 4
gpt4 key购买 nike

使用 Python 几个月后,我无法使用 BeautifulSoup 从表中抓取一些信息,如有任何帮助,我们将不胜感激。我没有收到任何错误代码,只是没有从表中收到任何数据。

import bs4 as bs
import requests

resp = requests.get('https://www.thestreet.com/markets/gainers.html')
soup = bs.BeautifulSoup(resp.text, "lxml")
table = soup.find('table', {'id': 'nyseData'})

tickers = []
for row in table.findAll('tr')[1:]:
ticker = row.findAll('td')[1].text
tickers.append(ticker)

非常感谢任何帮助!

最佳答案

您遇到的问题是页面不允许某些用户代理访问他们的站点。这可以通过在 requests header 中设置用户代理字符串来解决。

添加了用户代理的代码:

import bs4 as bs
import requests

headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}

resp = requests.get('https://www.thestreet.com/markets/gainers.html', headers=headers)
soup = bs.BeautifulSoup(resp.text,'lxml')
table = soup.find('table', {'id': 'nyseData'})

tickers = []
for row in table.findAll('tr')[1:]:
ticker = row.findAll('td')[1].text
tickers.append(ticker)

print tickers

输出:

[u'QUOT', u'BCEI', u'ATEN', u'SKX', u'FBK', u'FBM', u'CGI', u'SDRL', u'ELLI', u'CELP', u'SXCP', u'CUB', u'GLF', u'SID', u'HBM', u'NE', u'CBG', u'PJT', u'VVI', u'ARL']

关于python - Beautiful Soup 无法从表中获取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42184086/

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