Python 从html表中抓取数据,在标题之间选择元素
我试图从以下url中获取信息:使用此代码Python 从html表中抓取数据,在标题之间选择元素,python,beautifulsoup,Python,Beautifulsoup,我试图从以下url中获取信息:使用此代码 # Imports import requests from bs4 import BeautifulSoup credit_link = "http://www.mobygames.com/game/xbox360/wheelman/credits" response = requests.get(credit_link) soup = BeautifulSoup(response.text, "lxml") credit_infor= soup.fi
# Imports
import requests
from bs4 import BeautifulSoup
credit_link = "http://www.mobygames.com/game/xbox360/wheelman/credits"
response = requests.get(credit_link)
soup = BeautifulSoup(response.text, "lxml")
credit_infor= soup.find("div", class_="col-md-8 col-lg-8")
credit_infor1 = credit_infor.select('table[summary="List of Credits"]')[0].find_all('tr')
这是我需要获得的格式:
info credit_to studio game console
starring 138920 starring Wheelman Xbox 360
Studio Heads 151851 Midway Newcastle Studio Wheelman Xbox 360
Studio Heads 73709 Midway Newcastle Studio Wheelman Xbox 360
其中信息对应于每行的第一个“td”,信用卡对应于特定贡献者的id(例如138920是Vin Diesel的id),星号对应于标题。我想我可以处理一切,除了在每一排附近获得工作室名称(即标题)(稍后将从中途纽卡斯尔工作室切换到圣地亚哥QA团队等等)。我该怎么做呢?根据您的程序,
credit\u infor1
将列出所有tr
标记(行)。如果您检查HTML,即其中包含标题(studio)的行,则它们没有class
属性。对于所有其他行,它们具有class=“crln”
属性
因此,您可以迭代所有行,并使用函数检查当前行是否有class
作为属性(在文档中有些隐藏)。如果该属性不存在,请更改标题,否则继续刮除其他数据
继续您的计划:
studio = ''
for row in credit_infor1:
if not row.has_attr('class'):
studio = row.h2.text
continue
# get other values that you want from this row below
info = row.find('td').text
# similarly get all the other values you need each time
print(info + ' | ' + studio)
部分输出:
Starring | Starring
Studio Heads | Midway Newcastle Studio
Executive Producers | Midway Newcastle Studio
Technical Directors | Midway Newcastle Studio
Lead Programmers | Midway Newcastle Studio
...
QA Manager | San Diego QA Team
Compliance QA Manager | San Diego QA Team
QA Data Analyst | San Diego QA Team
...
SQA Analyst | SQS India QA
QA Team | SQS India QA
Executive Producers | Tigon Studios
Head of Game Production | Tigon Studios
...
您可以通过提取标题的内容来查找studio名称。请确保您忽略了Credits标题和Starting标题。但是我如何将其添加为附加行,例如,稍后QA经理将切换到“圣地亚哥QA团队”——Adam JonesI抱歉,我不太明白您的问题。但是,所有按顺序出现的标题都会更改。根据您的输出要求,如果您在
if
块之后刮取并打印数据,您将得到准确的结果。如果你愿意,我可以添加一些代码来展示一个例子。例如,工作室负责人Craig Duncan,Shaun Himmerick所属,Midway Newcastle Studio,但后来工作室更改了“圣地亚哥QA团队”,我需要说,当工作室是“Midway Newcastle Studio”时,将其写入工作室专栏,然后切换到下一个,明白了。您不需要切换列,只需打印每行的所有列,并在需要时更改值。我正在添加一个示例。。。