【问题标题】:Force python http request to refresh强制python http请求刷新
【发布时间】:2012-07-16 15:21:17
【问题描述】:

我是 python 新手,还没有发现任何表明这可能很容易的东西。

我要报废的页面相当简单,但它每 2 分钟完全更新一次。我设法废弃了所有数据,但问题是即使程序每 2 分钟运行一次(我已经尝试通过 taskeng.exe 并在脚本中循环),它从网站中提取的 html 似乎每 12 分钟刷新一次分钟。为了清楚起见,我要报废的网站在更新时有一个时间戳。我的程序提取该标记(连同其他数据)并写入 csv 文件。但是它提取相同的数据 12 分钟,然后突然数据到达。所以输出看起来像:

16:30, Data1, Data2, Data3
16:30, Data1, Data2, Data3
...
16:30, Data1, Data2, Data3
16:42, Data1, Data2, Data3
16:42, Data1, Data2, Data3

应该在哪里:

16:30, Data1, Data2, Data3
16:32, Data1, Data2, Data3
16:34, Data1, Data2, Data3
16:36, Data1, Data2, Data3
16:38, Data1, Data2, Data3
16:40, Data1, Data2, Data3
16:42, Data1, Data2, Data3

我认为这与我这边的缓存有关。如何强制我的 http 请求完全刷新或强制 python 不将其存储在缓存中?

我正在使用 BeautifulSoup 和 Mechanize。我的http请求代码如下:

mech = Browser()

url = "http://myurl.com"

page = mech.open(url)

html = page.read()
soup = BeautifulSoup(html)

如果发布我的所有代码有帮助,我可以这样做。提前感谢您的任何建议

【问题讨论】:

    标签: python http caching web-scraping


    【解决方案1】:

    您可以使用更简单的工具,例如 requests

    import requests
    response = requests.get(url)
    html = response.text
    

    但如果你真的想坚持使用机械化,你也可以跳过 Browser() 的东西(这可能会在你的请求中引入 cookie)。查看mechanize docs了解更多详情。

    response = mechanize.urlopen("http://foo.bar.com/")
    html = response.read() # or readlines 
    

    【讨论】:

    • 谢谢。这个请求模块非常有用。我认为你是对的,mechanize 不知何故对饼干做了一些事情。干杯。
    猜你喜欢
    • 1970-01-01
    • 2020-12-02
    • 2015-10-06
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多