【问题标题】:Obtain second tag inside a find_all获取 find_all 中的第二个标签
【发布时间】:2019-05-17 22:48:23
【问题描述】:

我正在尝试获取特定 td 内的第二个标签,但我无法仅获取第二个标签的文本,因为我正在从所有 a. 后面我会做一个for来获取10个td的数据。正如您在图片中看到的,我想要 10 个 td 中的每一个中的第二个 a 的数据:

我的代码:

from requests import get
from bs4 import BeautifulSoup

headers = {'User-Agent': 'Mozilla/5.0'}

url = 'https://www.oddsportal.com/soccer/spain/laliga'
response = get(url, headers=headers)

html_soup = BeautifulSoup(response.text, 'html.parser')
type(html_soup)



match_containers = html_soup.find_all("td",{ "class" : "name table-participant"})

print(len(match_containers))

first_match = match_containers[0]

first_title = first_match.text
print (first_title)

【问题讨论】:

    标签: python web-scraping beautifulsoup tags findall


    【解决方案1】:

    您需要选择第二个a标签

    import requests
    from bs4 import BeautifulSoup as bs
    
    url = 'https://www.oddsportal.com/soccer/spain/laliga'
    r = requests.get(url, headers = {'User-Agent' : 'Mozilla/5.0'})
    soup = bs(r.content, 'lxml')
    print([item.text for item in soup.select('#tournamentTable tr[xeid] [href*=soccer]')])
    

    虽然您可以删除表 id 并使用:

    print([item.text for item in soup.select('tr[xeid] [href*=soccer]')])
    

    对于表格的行,以有用的匹配数据作为列表,我会使用:

    rows = soup.select('#tournamentTable tr[xeid]')
    

    【讨论】:

    • 谢谢,我怎样才能一次获得 10 场比赛?
    • matches = [soup.select('.ico-tv-tournament ~ a') 中项目的 item.text ]
    • 你想要什么?
    • 不,ico-tv-tournament 只是为即将到来的比赛带来数据,而不是为表格中的所有比赛带来数据
    • 用这段代码我只得到一个匹配,而不是全部:from requests import get from bs4 import BeautifulSoup headers = {'User-Agent': 'Mozilla/5.0'} url = 'oddsportal.com/soccer/spain/laliga' response = get(url, headers=headers) html_soup = BeautifulSoup(response.text, 'html.parser') type(html_soup) match_containers = html_soup.find_all("td",{ "class" : "name table-participant"} ) first_match = match_containers[0].select_one('a:last-child') # td 中的最后一个 a(目前有效) first_title = first_match.text print (first_title)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多