【问题标题】:How to parse javascript results with Python如何使用 Python 解析 javascript 结果
【发布时间】:2014-04-18 12:49:14
【问题描述】:

我的 Python 脚本有问题。我想要做的就是用 id 值解析一个 div 元素:值并存储所有更改的值。这个元素的值是由 javascript 生成的。这意味着元素的值取决于用户的输入。更具体地说,html元素看起来像这样

<div id="value">...Here the frequently changed value generated by javascript...</div>

我的python脚本如下:

from bs4 import BeautifulSoup
import urllib
x=urllib.urlopen("http://example.com")
s = x.read()
soup = BeautifulSoup(s)

m = soup.find("div",{"id":"value"})
val = m.text
print val

结果是None,但是网页上的变化是很明显的!请帮我弄清楚。

【问题讨论】:

  • 您的代码看起来不错。您可以检查 x.getcode() 以确保您确实下载了该页面(它应该返回 200)。

标签: javascript python html beautifulsoup


【解决方案1】:

如果该值是由 javascript 生成的 - 最简单的解决方案是使用真正的浏览器来抓取网页。这就是selenium 可以提供帮助的地方。这是一个简单的例子:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://example.com')

element = browser.find_element_by_id('value')
print element.text

【讨论】:

  • 我在安装 selenium 模块时遇到了一些问题。 Splinter 是不是类似于 Selenium?
  • @ather0s splinter 只是 selenium 和其他库之上的一个抽象层。
猜你喜欢
  • 2014-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-02
  • 1970-01-01
  • 1970-01-01
  • 2013-08-24
相关资源
最近更新 更多