【问题标题】:python urllib2 - reading a page after all scripts ranpython urllib2 - 在所有脚本运行后读取页面
【发布时间】:2015-03-22 00:08:04
【问题描述】:

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

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

<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

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

【问题讨论】:

    标签: python html urllib2


    【解决方案1】:

    表中填充了附加 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
    

    【讨论】:

    • 似乎我们很一致地回答了同一个问题;)
    • @Anzel 是的,我们需要调整我们的日程安排 :)
    • 这似乎少了一点开销(与打开浏览器相比),但数据的格式很奇怪:)
    • @alecxe,你是怎么找到合适的php方法的?
    • @Quantico 刚刚使用了浏览器开发工具(网络选项卡)。是的,我意识到这种方法是一种低级裸机方法,而不是高级硒选项。谢谢。
    【解决方案2】:

    如果 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
    

    【讨论】:

    • 我会试一试,然后报告
    • 工作。我选择了另一个答案,因为它的开销较小。
    • @Quantico,我当然很满意。是的,alecxe 的答案非常可靠,您可以了解 WHY 元素最初不在页面中的原因。彻底了解 HTML 的工作原理肯定会让您在未来受益 :)
    【解决方案3】:

    一开始我会去:

    bs = BeautifulSoup(the_page)
    html = bs.html
    

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

    print str(BeautifulSoup(the_page))
    

    将显示 Beautiful Soup 将页面解析成的内容。

    【讨论】:

    • beautifulSoup 的问题是它无法访问从脚本生成的数据
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多