[英]How do I find the right element for my web-scraping?
我試圖從 Transfermarkt 上排名前 25 位的最有價值球員那里獲得盡可能多的信息。 我設法獲得了一些信息(在同事和 stackoverflow 的幫助下),現在我正在嘗試獲取球員位置,我覺得這很難,因為它看起來與其他元素不同(在我看來)。 我是這方面的初學者,所以任何源材料或直接的代碼幫助都是有幫助的。 鏈接到我正在抓取的網站: Transfermarkt
我嘗試通過不同的路徑到達元素,但我似乎無法理解。 我在 crummy.com 上閱讀了有關 bs4 的內容,並在 stackoverflow 上查看了其他 transfermarkt 示例,但是我對編碼的不了解給我帶來了麻煩。 我正在測試我的主代碼之外的不同類型的元素,看看我是否得到了正確的結果。
我的測試代碼看起來像這樣,打印沒有給出任何內容。
import requests
from bs4 import BeautifulSoup
import re
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0'
}
r = requests.get(
"https://www.transfermarkt.co.uk/spieler-statistik/wertvollstespieler/marktwertetop", headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')
for position in soup.find_all("td",class_="inline_table"):
print(position)
從 VarKas 答案開始工作,但重新調整到您的原始嘗試,如果您使用類'inline-table'
查找'table'
,它會分別抓取帶有玩家姓名和位置的“迷你桌子”作為第 1 行和第 2 行:
for table in soup.find_all('table', attrs={'class': 'inline-table'}):
content = table.contents
print(content[0].text) # Name
print(content[1].text) # Position
此外,如果您想查找前 25 個以上的頁面,您可以通過在 URL 中添加'?page='
來快速瀏覽表格的所有頁面(有 20 個):
import requests
from bs4 import BeautifulSoup
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0'
}
pages = range(1, 20)
for page in pages:
r = requests.get(
"https://www.transfermarkt.co.uk/spieler-statistik/wertvollstespieler/marktwertetop?page=%d" % page, headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')
pretty = soup.prettify()
for table in soup.find_all('table', attrs={'class': 'inline-table'}):
content = table.contents
print(content[0].text) # Name
print(content[1].text) # Position
使用此代碼
import requests
from bs4 import BeautifulSoup
import re
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0'
}
r = requests.get(
"https://www.transfermarkt.co.uk/spieler-statistik/wertvollstespieler/marktwertetop", headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find_all("table", {"class": "inline-table"})
# table[0] ---> Mbape Data
# table[1] --->Raheem Sterling Data
# table[2] ---> Neymar Data
print(table[0].find_all('a')[1].get_text()) # Mbape Name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.