python urllib2 - 在所有脚本之后读取页面 运行

python urllib2 - reading a page after all scripts ran

我正在尝试使用 urllib2 读取页面,以便从页面中提取数据。页面的一部分是每次加载生成的,当我用 urllib2 阅读 url 时,这部分不在我得到的 html 中。

url 是 http://nametrends.net/name.php?name=Ruby ,我正在尝试获取为图形生成的 table 。 例如:

<div aria-label="A tabular representation of the data in the chart." style="position: absolute; left: -10000px; top: auto; width: 1px; height: 1px; overflow: hidden;">
        <table>
            <tbody>
            <tr><td>Sat Feb 01 1947 00:00:00 GMT-0500 (EST)</td><td>0.048</td><td>0</td></tr>
            </tbody>
         </table>
</div>

我当前的代码是:

import urllib2
from bs4 import BeautifulSoup
req = urllib2.Request('http://nametrends.net/name.php?name=Ruby')
response = urllib2.urlopen(req)
the_page = response.read()

html = BeautifulSoup(the_page)
print "tabular" in html
for table in html.find_all('table'):
    print 1

它没有找到 table ,并且 html 中没有 div 文本表格(这是 div 的标签包含table)

table 填充了附加 XHR 请求返回到 getfrequencyjson.php 端点的数据。您需要在代码中发出该请求并解析 JSON 数据:

import requests

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36'}

with requests.Session() as session:
    session.headers = headers
    session.get('http://nametrends.net/name.php', params={'name': 'ruby'}, headers=headers)

    response = session.get('http://nametrends.net/chartdata/getfrequencyjson.php', params={'name': 'ruby'})
    results = response.json()
    print results

如果 urllib2 以外的替代方案是可能的,Selenium 可以轻松执行此类任务,并使用实际的浏览器模拟:

from selenium import webdriver
from bs4 import BeautifulSoup

url = 'http://nametrends.net/name.php?name=Ruby'
driver = webdriver.Firefox()
driver.get(url)
# wait until 'tabular' appears on browser
assert 'tabular' not in driver.page_source

html = BeautifulSoup(driver.page_source)
for table in html.find_all('table'):
    print table

一开始我会去:

bs = BeautifulSoup(the_page)
html = bs.html

您的代码看起来不错。去...

print str(BeautifulSoup(the_page))

将显示 Beautiful soup 将页面解析成什么。