【问题标题】:Set cookie in BeautifulSoup Python web scraper在 BeautifulSoup Python 网络爬虫中设置 cookie
【发布时间】:2016-10-24 01:22:39
【问题描述】:

我正在尝试创建一个 python 脚本,该脚本可以访问网页并检查其中是否存在具有指定 id 的 div,如果没有,它会再次尝试删除给定的 cookie。

到目前为止,这是我的代码:

import urllib2
from BeautifulSoup import BeautifulSoup
import time

url = 'http://google.com'
cookie = 'hello'

while True:
    page = urllib2.urlopen(url).read()
    soup = BeautifulSoup(page)
    soup.prettify()
    if soup.find(id='hello'):
        print "Found!"
        break
    else:
        #DELETE THE GIVEN COOKIE AND TRY AGAIN
    time.sleep(1)

我的要求是:如何删除 cookie?或者我不需要删除它,因为 BeautifulSoup 会使用不同的实例重试请求?

另外,是否可以使用此方法设置标头、用户代理等内容?如果有,怎么做?

【问题讨论】:

    标签: python cookies web-scraping beautifulsoup


    【解决方案1】:

    您无需在此处删除 cookie。每次使用 urlopen() 方法请求 url 时,它都会请求页面的新副本。但是,如果您确实需要保存 cookie,我推荐使用 python requests 库或 mechanize,它们都可以让您保存浏览器会话。

    还可以在您拥有的代码中添加标头和用户代理。

    import urllib2
    from BeautifulSoup import BeautifulSoup
    import time
    
    url = 'http://google.com'
    
    opener = urllib2.build_opener()
    opener.addheaders = [('User-agent', 'Mozilla/5.0')]
    
    while True:
        page = opener.open(url).read()
        soup = BeautifulSoup(page)
        soup.prettify()
        if soup.find(id='hello'):
            print "Found!"
            break
        else:
            time.sleep(1)
    

    【讨论】:

      猜你喜欢
      • 2015-05-12
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多