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

Tag*_*agc 7 html python templates urllib

我正在使用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)
Run Code Online (Sandbox Code Playgroud)

在我试图找到特定值的地方,我找到了一个模板,例如"{{formatPrice median}}"而不是"4.48".

我怎样才能使它能够检索值而不是占位符文本?

编辑:是我正在尝试从中提取信息的特定页面.我正在尝试获取"中位数"值,该值使用模板{{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
Run Code Online (Sandbox Code Playgroud)

是程序正在执行的屏幕截图.不幸的是,它似乎没有找到指定"formatPrice median"的任何内容.

wil*_*art 17

假设您正在尝试从使用javascript模板呈现的页面中获取值(例如像把手一样),那么这就是您将使用任何标准解决方案(即beautifulsouprequests)获得的.

这是因为浏览器使用javascript来改变收到的内容并创建新的DOM元素.urllib将像浏览器一样执行请求部分,而不是模板渲染部分.可在此处找到有关问题的详细说明.本文讨论了三个主要解决方案:

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

这个答案为选项3提供了一些建议,例如selenium或watir.我已经使用硒进行自动化网络测试,非常方便.


编辑

从您的评论看起来它是一个车把驱动的网站.我推荐硒和美味的汤. 这个答案提供了一个很好的代码示例,它可能很有用:

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
Run Code Online (Sandbox Code Playgroud)

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