【问题标题】:Simulating cookies with python web crawler使用 python 网络爬虫模拟 cookie
【发布时间】:2020-03-07 04:43:02
【问题描述】:

我需要一些帮助。我正在尝试使用“请求”库和 BeautifulSoup4 库创建一个网络爬虫,但为了成功,我必须访问一个链接来激活特定的 cookie,以便我搜索该查询的内容。

import requests
from bs4 import BeautifulSoup

def web_spider(max_pages, query):
    page = 1
    while page <= max_pages:
        url = r'http://website.com/search/index?page=' + str(page) + '&q=' + query
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text)
        for link in soup.finaAll('a', {'class': 'comments_link'}):
            href = 'http://website.com/' + link.get('href')
            print(href)
        page += 1

问题在于某些查询,除非某个 cookie 设置由 url 触发,否则由于未启用正确的 cookie,它不会显示任何内容。根据我的代码的当前功能,我采取的最佳行动方案是什么?

【问题讨论】:

    标签: python cookies python-3.x


    【解决方案1】:

    使用Session() object 会自动处理cookies:

    session = requests.Session()
    
    def web_spider(max_pages, query):
        page = 1
        while page <= max_pages:
            url = 'http://website.com/search/index'
            params = {'page': page, 'q': query}
            source_code = session.get(url, params=params)
            plain_text = source_code.content
            soup = BeautifulSoup(plain_text)
            for link in soup.select('a.comments_link[href]'):
                href = 'http://website.com/' + link['href']
                print(href)
            page += 1
    

    全局 session 对象现在跟踪所有 cookie。

    我还更改了您的代码以使用 params 参数以具有 requests 句柄编码,并且您应该在解析 HTML 时使用 response.content response.text,以确保BeautifulSoup 检测到正确的编码

    【讨论】:

    • 当我输入 'session = Session()' 时,我收到一条错误消息“未解析的引用 'Session'”
    • 我把它改成 'session = requests.Session()' 可以吗?
    • @ThatBenderGuy:是的,对不起,我的错误。
    • 最后一个问题,session.get('http://website.com/cookieToggle') 应该放在哪里?
    • 或者更好(抱歉有这么多问题)我如何查看python为该会话存储的当前cookie?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多