我正在为一个大学项目做准备,我想从 IMbd 上抓取电视节目的类型。在图像中你可以找到 html。我使用了以下代码:
url1 = 'https://m.imdb.com/title/tt0903747/?ref_=chttvtp_t_1'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'}
response1 = requests.get(url1, headers=headers)
soup1 = BeautifulSoup(response1.content, 'html.parser')
genres= soup1.find("a", class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link").text
print(genres)
但它刮掉了“Creation”,即位于网站开头且具有相同的类名,而不是流派。
我尝试使用 soup.find_all 这样我就可以使用该特定类来抓取所有 ele,emts,但它给了我错误“ResultSet 对象没有属性‘text’。您可能将元素列表视为单个元素。当您打算调用 find() 时,您是否调用了 find_all() ?” 问题出在哪里?
我还想将该函数应用于我抓取的所有网址,但我不太擅长 for 循环。我如何创建一个 for 循环来将该函数应用于此数据框:
tvshows_url= pd.DataFrame(
[
{
'link':f'https://www.imdb.com{link.get("href")}',
'title': link.text.split('. ')[-1]
}
for link in soup.select('a[href^="/title"]:has(h3)')
]
)
print(tvshows_url)
您必须更具体地选择元素,始终考虑其父母或兄弟姐妹。在这种情况下,我使用了
css selectors
和带有参数的 get_text()
来连接/拆分文本:
genres= soup1.select_one('[data-testid="genres"]').get_text('|', strip=True)
print(genres)
导致:
Crime|Drama|Thriller
但是,您可以在关注一些脚本数据并将其直接加载到数据框中时使其变得更容易:
import requests, json
from bs4 import BeautifulSoup
import pandas as pd
url = "https://www.imdb.com/chart/toptv/"
soup = BeautifulSoup(
requests.get(url,headers={'user-agent':'some-agent'}).content,
"html.parser"
)
data = []
for link in soup.select('a[href^="/title"]:has(h3)')[:3]:
data.append(
json.loads(
BeautifulSoup(
requests.get(f'https://www.imdb.com{link.get("href")}',headers={'user-agent':'some-agent'}).content,
"html.parser"
).find("script", {"type": "application/ld+json"}).text
)
)
pd.json_normalize(data)