首页 > 解决方案 > 尝试使用 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()?
>>>

标签: pythonhtmlweb-scrapingbeautifulsoup

解决方案


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(...) 

推荐阅读