gpt4 book ai didi

python - 如何使用 Python 检索动态 html 内容的值

转载 作者:太空狗 更新时间:2023-10-29 14:44:06 24 4
gpt4 key购买 nike

我正在使用 Python 3 并尝试从网站检索数据。但是,此数据是动态加载的,我现在拥有的代码不起作用:

url = eveCentralBaseURL + str(mineral)
print("URL : %s" % url);

response = request.urlopen(url)
data = str(response.read(10000))

data = data.replace("\\n", "\n")
print(data)

在我尝试查找特定值的地方,我找到了一个模板,例如“{{formatPrice median}}”而不是“4.48”。

如何才能获取值而不是占位符文本?

编辑:This是我试图从中提取信息的特定页面。我正在尝试获取使用模板 {{formatPrice median}}

的“中位数”值

编辑 2:我已经安装并设置了我的程序以使用 Selenium 和 BeautifulSoup。

我现在的代码是:

from bs4 import BeautifulSoup
from selenium import webdriver

#...

driver = webdriver.Firefox()
driver.get(url)

html = driver.page_source
soup = BeautifulSoup(html)

print "Finding..."

for tag in soup.find_all('formatPrice median'):
print tag.text

Here是程序执行时的屏幕截图。不幸的是,它似乎没有找到任何指定了“formatPrice median”的东西。

最佳答案

假设您正在尝试从使用 javascript 模板呈现的页面中获取值(例如类似 handlebars 的内容),那么这就是您将使用任何标准解决方案(即 beautifulsoup 请求)。

这是因为浏览器使用 javascript 来更改它接收到的内容并创建新的 DOM 元素。 urllib 将像浏览器一样执行请求部分,而不是模板渲染部分。 A good description of the issues can be found here .本文讨论三种主要解决方案:

  1. 直接解析ajax JSON
  2. 使用离线 Javascript 解释器处理请求 SpiderMonkey , crowbar
  3. 使用浏览器自动化工具 splinter

This answer为选项 3 提供更多建议,例如 selenium或 watir。我使用 selenium 进行自动化 Web 测试,它非常方便。


编辑

从您的评论来看,它似乎是一个 Handlebars 驱动的网站。我会推荐 Selenium 和美丽的汤。 This answer给出了一个可能有用的很好的代码示例:

from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://eve-central.com/home/quicklook.html?typeid=34')

html = driver.page_source
soup = BeautifulSoup(html)

# check out the docs for the kinds of things you can do with 'find_all'
# this (untested) snippet should find tags with a specific class ID
# see: http://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class
for tag in soup.find_all("a", class_="my_class"):
print tag.text

基本上,selenium 从您的浏览器获取呈现的 HTML,然后您可以使用 page_source 属性中的 BeautifulSoup 解析它。祝你好运:)

关于python - 如何使用 Python 检索动态 html 内容的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17597424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com