我正在与BeautifulSoup斗争。我想在[Transmarkmarkt] [1]右侧的表格中抓取比赛的链接
到目前为止,我如何定位它:
div1 = soup.find('div', {'class': 'large-4 columns'})
div2 = div1.find('div', {'class': 'box'})
table = div2.find('table')
table_body = table.find('tbody')
contest = table_body.find_all('a')
问题是,这还不够具体。有时我会发现双精度值,这完全破坏了我的结构...
有没有更好的方法来定位这个确切位置?
我需要的位置:“ td”“ class = noborder-links”内的“ a”“ title”
答案 0 :(得分:2)
在这种情况下,最好使用select
。
for title in soup.select('.large-4.columns td.no-border-links > a'):
if title.text:
print(title.text)
输出将为
Weltmeisterschaft 2014
UEFA Champions League
1.Bundesliga
1.Bundesliga
1.Bundesliga
1.Bundesliga
FC Bayern München
1.Bundesliga
UEFA Champions League
1.Bundesliga
1.Bundesliga
1.Bundesliga
Deutschland
Deutschland
Weltmeisterschaft 2018
Weltmeisterschaft 2014
Weltmeisterschaft 2010
Europameisterschaft 2016
Europameisterschaft 2012
Weltmeisterschaft 2014
U21-Europameisterschaft 2009
UEFA Champions League
1.Bundesliga
Weltmeisterschaft 2010
Deutschland
UEFA Champions League
UEFA Champions League
UEFA Champions League
UEFA Champions League
UEFA Champions League
UEFA Champions League
UEFA Champions League
UEFA Champions League
UEFA Champions League
UEFA Super Cup
FC Bayern München
FC Bayern München
FC Bayern München
Deutschland
FIFA Klub-WM
DFB-Pokal
DFB-Pokal
DFB-Pokal
DFB-Pokal
DFL-Supercup
DFL-Supercup
DFL-Supercup
DFB-SuperCup
DFB-Pokal
U21-Europameisterschaft 2009
答案 1 :(得分:1)
尝试以下操作以获得所需的内容:
import re
import requests
from bs4 import BeautifulSoup
URL = "https://www.transfermarkt.de/jumplist/erfolge/spieler/17259"
res = requests.get(URL,headers={"User-Agent":"Mozilla/5.0"})
soup = BeautifulSoup(res.text,"lxml")
for items in soup.select(".table-header:contains('Alle Titel') + table tr"):
if not items.find("a",string=re.compile("\w")):continue
item = items.find("a",string=re.compile("\w")).text
print(item)
要获取链接,请尝试以下操作:
import re
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
URL = "https://www.transfermarkt.de/jumplist/erfolge/spieler/17259"
res = requests.get(URL,headers={"User-Agent":"Mozilla/5.0"})
soup = BeautifulSoup(res.text,"lxml")
for items in soup.select(".table-header:contains('Alle Titel') + table tr"):
if not items.find("a",string=re.compile("\w")):continue
item = items.find("a",string=re.compile("\w")).text
try:
link = urljoin(URL,items.select_one("a[href^='/']").get("href"))
except AttributeError: link = ""
print(item,link)
答案 2 :(得分:0)
尝试在汤库中使用select
函数,您可以在其中使用CSS selectors。
在您的情况下,您可以使用类似-
a_tags = soup.select("td[class='no-border-links'] > a")
现在,您可以使用text
属性对其进行迭代以获取标题。