【问题标题】:Content of a page changing at each request每次请求都会更改页面的内容
【发布时间】:2019-07-10 14:36:52
【问题描述】:

我正在尝试从存储有关法国公司的各种信息的网站上抓取 HTML 页面。但是,每次我通过 pd.read_html 发送请求(仅提取表格)时,都会得到不同的结果。

为了说明我的观点,你会发现一些代码可以重现:

result = []
for i in range(0,10):
    result.extend(pd.read_html('https://www.societe.com/societe/eram-388583239.html', encoding='utf-8',attrs={'id':'rensjur'}))
    time.sleep(5)
print(result)

我希望得到与在浏览器中打开链接时相同的表格。

【问题讨论】:

    标签: python pandas web-scraping beautifulsoup


    【解决方案1】:

    玩了几分钟后,我发现更改用户代理会有所帮助。我的猜测是,当网站检测到不是网络浏览器的用户代理时,它会混淆真实数据。

    我确信有一种更优雅的方法可以做到这一点,但这里是我使用的代码,它每次都提取相同的数据:

    import pandas as pd
    import time
    import urllib.request as request
    
    results = []
    for i in range(0,10):
        url = 'https://www.societe.com/societe/eram-388583239.html'
        opener = request.build_opener()
        opener.addheaders = [('User-agent', 'Mozilla/5.0')]
        response = opener.open(url)
        result = pd.read_html(response.read(), encoding='utf-8',attrs={'id':'rensjur'})
        print(result)
        results.extend(result)
        time.sleep(5)
    print(results)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-01
      • 1970-01-01
      • 2013-11-29
      • 2014-01-15
      • 1970-01-01
      • 2020-02-21
      相关资源
      最近更新 更多