我正在尝试从此链接链接示例中提取排名文本编号:kaggle用户排名no1。图像更清晰:
我正在使用以下代码:
def get_single_item_data(item_url):
sourceCode = requests.get(item_url)
plainText = sourceCode.text
soup = BeautifulSoup(plainText)
for item_name in soup.findAll('h4',{'data-bind':"text: rankingText"}):
print(item_name.string)
item_url = 'https://www.kaggle.com/titericz'
get_single_item_data(item_url)
结果是None
。问题是soup.findAll('h4',{'data-bind':"text: rankingText"})
输出:
[<h4 data-bind="text: rankingText"></h4>]
但是在检查时链接的html中是这样的:
<h4 data-bind="text: rankingText">1st</h4>
。可以在图中看到:
很明显,文本丢失了。我该如何超越?
因此,应该有一种通过进行访问的方法soup
。
编辑2:我尝试使用此stackoverflow问题中投票率最高的答案,但未成功。可能是周围的解决方案。
如果您不打算selenium
按照@Ali的建议尝试通过浏览器自动化,则必须解析包含所需信息的javascript。您可以通过不同的方式来执行此操作。这是一个工作代码,该代码script
通过正则表达式模式定位,然后提取profile
对象,将其加载json
到Python字典中,并打印出所需的排名:
import re
import json
from bs4 import BeautifulSoup
import requests
response = requests.get("https://www.kaggle.com/titericz")
soup = BeautifulSoup(response.content, "html.parser")
pattern = re.compile(r"profile: ({.*}),", re.MULTILINE | re.DOTALL)
script = soup.find("script", text=pattern)
profile_text = pattern.search(script.text).group(1)
profile = json.loads(profile_text)
print profile["ranking"], profile["rankingText"]
印刷:
1 1st
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句