Python 如何为我的网页抓取找到合适的元素?

Python 如何为我的网页抓取找到合适的元素?,python,web-scraping,beautifulsoup,Python,Web Scraping,Beautifulsoup,我正试图从Transfermarkt排名前25的最有价值球员那里获得尽可能多的信息。在同事和stackoverflow的帮助下,我设法获得了一些信息,现在我正试图获得球员的位置,我发现这很难,因为在我看来,这与其他因素不同。我是这方面的初学者,所以任何源材料或代码的直接帮助都是有帮助的。链接到我正在抓取的网站: 我尝试过通过不同的途径接触元素,但似乎无法实现。我在crumy.com上读过关于bs4的内容,并在stackoverflow上查看了其他transfermarkt示例,但我对编码的糟糕知

我正试图从Transfermarkt排名前25的最有价值球员那里获得尽可能多的信息。在同事和stackoverflow的帮助下,我设法获得了一些信息,现在我正试图获得球员的位置,我发现这很难,因为在我看来,这与其他因素不同。我是这方面的初学者,所以任何源材料或代码的直接帮助都是有帮助的。链接到我正在抓取的网站:

我尝试过通过不同的途径接触元素,但似乎无法实现。我在crumy.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)
使用此代码

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

从VarKas answer开始工作,但重新调整到您最初的尝试,如果您使用类“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

干得好请更具体地说明问题所在。堆栈溢出不是代码编写服务,也不是指南或教程资源,请参阅和。嗨,AMC!我明白,我是新来这里的,我还不完全明白,所以我的基本问题是。但我认为这不值得投反对票。感谢您的反馈,祝您度过愉快的一周。