python - 尝试使用 python 和 bs4 从特定 'td' 中抓取所有 'a' 文本
问题描述
我正在尝试抓取https://www.betexplorer.com/soccer/england/premier-league/fixtures/以提取“a”标签中包含的文本,特别是在带有“table-main”类的表中,然后对于其中的每一行。第一个 td 包含带有两个团队名称的文本,td 类为“h-text-left”。不确定问题是否与我的循环有关,但我收到的错误消息似乎是我在循环的最后一行错误地使用了 bs4。
我可以用类“table-main”刮掉表中的每个 tr,然后再用类“h-text-left”刮掉每个 td。我在尝试单独提取“a”元素时遇到了死胡同,甚至没有“a”文本。
import requests
from bs4 import BeautifulSoup
headers = {'User-Agent':
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}
r = requests.get('https://www.betexplorer.com/soccer/england/premier-league/fixtures/', headers=headers)
c = r.content
soup = BeautifulSoup(c)
fixture_table = soup.find('table', attrs = {'class': 'table-main'})
for tr in soup.find_all('tr'):
match_tds = tr.find_all('td', attrs = {'class': 'h-text-left'})
matches = match_tds.find_all('a')
当我尝试查找所有“a”标签时,最后一行出现以下错误:
... matches = match_tds.find_all('a')
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "C:\Users\Glypt\AppData\Local\Programs\Python\Python36-32\lib\site-packages\bs4\element.py", line 1884, in __getattr__
"ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key
AttributeError: ResultSet object has no attribute 'find_all'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?
>>>
解决方案
match_tds
是一个列表,而不是单个元素 - 你得到它tr.find_all(...)
- 所以你必须使用for
循环来运行另一个find_all()
for tr in soup.find_all('tr'):
match_tds = tr.find_all('td', attrs = {'class': 'h-text-left'})
for item in match_tds:
matches = item.find_all('a')
for a in matches:
print(a['href'])
如果您使用find()
获取第一个元素,那么您可以与另一个find()
或find_all()
soup.find(...).find(...).find_all(...)
但你不能使用find()
或find_all()
之后find_all()
# ERROR
soup.find_all(...).find_all(...)
# ERROR
soup.find_all(...).find(...)
推荐阅读
- typescript - 是否可以在 TypeScript 中递归地推断泛型类型?
- python - 如何在python中正确预白时间序列
- python - 在 pyinstaller 中使用 base_library.zip 文件
- android - 如何从我的资产文件夹中访问 .docx 文件?
- r - 在 R 中使用绑定 tf_df
- python-3.x - 子类的父类中的参数使用什么类型提示?
- javascript - 直接评估 JavaScript AST
- java - 如果我只使用一次,我应该散列用户输入的密码吗?
- javascript - JavaScript 新手,需要将输入返回给函数的调用者。我做得对吗?
- javascript - 使用 react、redux、firestore 提交表单 - 未在 firestore 中创建集合