我正在嘗試從 IMDB 抓取前 250 部電影的資料。
from bs4 import BeautifulSoup
import requests
import pandas as pd
url="https://www.imdb.com/chart/top/?ref_=nv_mv_250"
page=requests.get(url).content
soup=BeautifulSoup(page,"html.parser")
data=[]
titles=soup.find_all("td",class_="titleColumn")
ratings=soup.find_all("td",class_="ratingColumn imdbRating")
for title,rating,year in zip(titles,ratings,years):
data.append({"Title":title.text.replace("\n",""),
"Rating":rating.text.replace("\n","")})
pd.DataFrame(data)
我得到了這個結果:

如您所見,標題列包括電影的索引、標題和發行年份。我想在不同的列中分別獲取這些文本。

uj5u.com熱心網友回復:
您可以使用str.extract. 您不需要requests,bs4在這里,您可以直接獲取資料pd.read_html:
# Get the table
df = pd.read_html(url)[0]
# Extract Rank, Title, Year from 'Rank & Title' column
pat = r'(?P<Rank>\d )\.\s (?P<Title>[^\(] )\s \((?P<Year>\d{4})\)'
df1 = df['Rank & Title'].str.extract(pat).astype({'Rank': int, 'Year': int})
# Merge previous dataframe with 'IMDb Rating' column
out = pd.concat([df1, df['IMDb Rating'].rename('Rating')], axis=1)
輸出:
>>> out
Rank Title Year Rating
0 1 Les évadés 1994 9.2
1 2 Le Parrain 1972 9.2
2 3 The Dark Knight : Le Chevalier noir 2008 9.0
3 4 Le Parrain, 2? partie 1974 9.0
4 5 12 Hommes en colère 1957 8.9
.. ... ... ... ...
245 246 Aladdin 1992 8.0
246 247 Gandhi 1982 8.0
247 248 La couleur des sentiments 2011 8.0
248 249 La Belle et la Bête 1991 8.0
249 250 Danse avec les loups 1990 8.0
[250 rows x 4 columns]
>>> out.dtypes
Rank int64
Title object
Year int64
Rating float64
dtype: object
uj5u.com熱心網友回復:
你可以試試.str.extract
df['rank'] = df['Title'].str.extract('^(\d )\.')
df['year'] = df['Title'].str.extract('\((\d )\)$')
df['Title'] = df['Title'].str.extract('^\d \. (.*) \(\d \)$')
print(df)
Title rank year
0 The Shawshank Redemption 1 1994
1 The Godfather 2 1972
2 The Dark Knight 3 2008
3 The Godfather Part II 4 1974
4 12 Angry Men 5 1957
uj5u.com熱心網友回復:
用一個和使用全選<tr>來提取和分離行中每個元素的文本值:<table><td>.stripped_strings
for e in soup.select('table[data-caller-name="chart-top250movie"] tr:has(td)'):
data.append(dict(zip(['rank','name','year','rating'],e.stripped_strings)))
要擺脫年份列中的“()”,您可以replace()這樣:
df.year = df.year.str.replace(r'[()]','', regex=True)
例子
from bs4 import BeautifulSoup
import requests
import pandas as pd
url="https://www.imdb.com/chart/top/?ref_=nv_mv_250"
page=requests.get(url).content
soup=BeautifulSoup(page,"html.parser")
data=[]
for e in soup.select('table[data-caller-name="chart-top250movie"] tr:has(td)'):
data.append(dict(zip(['rank','name','year','rating'],e.stripped_strings)))
df = pd.DataFrame(data)
df.year = df.year.str.replace(r'[()]','', regex=True)
df
輸出
| 秩 | 姓名 | 年 | 評分 | |
|---|---|---|---|---|
| 0 | 1 | 死亡 | 1994 | 9.2 |
| 1 | 2 | 德佩特 | 1972年 | 9.2 |
| 2 | 3 | 黑暗騎士 | 2008年 | 9.0 |
| 3 | 4 | 德佩特 2 | 1974年 | 9.0 |
| 4 | 5 | Die zw?lf Geschworenen | 1957年 | 8.9 |
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/489022.html
上一篇:將html腳本變數提取為JSON
下一篇:需要網站上的鏈接和文字
