我正在尝试获取此url中的所有表=”https://www.topuniversities.com/university-rankings/university-subject-rankings/2021/psychology".
问题是没有table
标记,也没有<tr>
和<td>
标记。行中的所有数据都在嵌套的“div”标记中。
我使用的代码是:
from bs4 import BeautifulSoup
from selenium import webdriver
from webdriver_manager.firefox import GeckoDriverManager
import time
driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
driver.maximize_window()
driver.get(url)
time.sleep(5)
content = driver.page_source.encode('utf-8').strip()
soup = BeautifulSoup(content,"html.parser")
driver.quit()
print(soup)
另外,我只从嵌套的<div>
标记中的一列(名为“totalscore”的列)获取数据。
我还意识到,soup
输出中只有前10行的数据,但我正在尝试获取所有302行的数据
非常感谢你能给我的任何建议
编辑
在@KunduK
的回答之后,我设法得到了我所期望的结果。这是我最后使用的代码:
res = requests.get('https://www.topuniversities.com/sites/default/files/qs-rankings-data/en/3519089_indicators.txt?1614801117').json()
df = pd.DataFrame(res["data"])
df = df[["uni", "region", "location", "city", "overall",
"ind_69", "ind_70", "ind_76", "ind_77"]]
headers = {"uni":"University", "overall": "Overall Score", "ind_69": "H-index Citations",
"ind_70": "Citations per Paper", "ind_76": "Academic Reputation", "ind_77": "Employer Reputation"}
df.rename(columns=headers, inplace=True)
for column in headers.values():
df[column] = df[column].apply(lambda value: BeautifulSoup(value, 'html.parser').find('div').text)
df
您不需要selenium,如果您转到网络选项卡,您将看到下面的链接,该链接以json的形式返回数据。您需要遍历它并获取值
代码:
输出:
网络选项卡
我已经检查了您提供的URL。似乎数据(从XHR请求@https://www.topuniversities.com/sites/default/files/qs-rankings-data/en/3519089.txt?1616049862?v=1616050007711接收)是通过分页进行拆分的,这就是为什么您只看到其中的10个条目
处理此问题有两种选择:
相关问题 更多 >
编程相关推荐