使用Python解析带有JavaScript调用的网站
因为我在常见的维基媒体上找不到一个可以获取图片许可证的API函数,所以我只能自己去抓取网页并解析内容。
每张图片在维基媒体上都有一个很不错的弹出窗口,里面列出了我需要的“归属”字段。比如,在这个页面 http://commons.wikimedia.org/wiki/File:Brad_Pitt_Cannes_2011.jpg 上,右边有一个链接写着 "在网上使用这个文件"
。点击这个链接后,我就能看到我需要的“归属”字段。
我想用Python来抓取这个网页,并启动一个JavaScript调用来打开那个弹出窗口,以便获取“归属”字段里的文本。你能告诉我怎么做吗?
谢谢!
meir
3 个回答
1
假设你能看懂Javascript,你可以查看这个Javascript文件:http://commons.wikimedia.org/w/index.php?title=MediaWiki:Stockphoto.js&action=raw&ctype=text/javascript
你可以看看这个Javascript是怎么获取信息的(关注一下 get_author_attribution
和 get_license
这两个部分)。你可以用 BeautifulSoup
这个工具把它转换成Python代码来解析HTML。
1
我很想看看用其他工具怎么做到这一点。使用Selenium RC和lxml,可以这样做:
import selenium
sel=selenium.selenium("localhost",4444,"*firefox", "file://")
sel.start()
sel.open('http://commons.wikimedia.org/wiki/File%3aBrad_Pitt_Cannes_2011.jpg')
sel.click('//a[contains(@title,"Use this file on the web")]')
print(sel.get_value('//input[@id="stockphoto_attribution"]'))
sel.stop()
结果是
Georges Biard [CC-BY-SA-3.0 (www.creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons
4
根据unutbu的回答,我把它改成了使用Selenium的WebDriver(而不是之前的Selenium-RC)。
import codecs
import lxml.html as lh
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://commons.wikimedia.org/wiki/File%3aBrad_Pitt_Cannes_2011.jpg')
content = browser.page_source
browser.quit()
doc = lh.fromstring(content)
for elt in doc.xpath('//span[a[contains(@title,"Use this file")]]/text()'):
print elt
输出结果:
on the web
on a wiki