【问题标题】:How to set session cookie while extracting contents from URLs using beautiful soup?如何在使用漂亮的汤从 URL 中提取内容时设置会话 cookie?
【发布时间】:2015-08-07 14:57:59
【问题描述】:

考虑代码:

from bs4 import BeautifulSoup
from urllib.request import urlopen
content = urlopen('https://example.net/users/101')
soup = BeautifulSoup(content)
divTag = soup.find_all("div", {"class":"classname"})
print(divTag)
for tag in divTag:
   ulTags = tag.find_all("ul", {"class":"classname"})
   for tag in ulTags:
       aTags = tag.find_all("li")
       for tag in aTags:
           name = tag.find('a')['href']
           print(name)

如果我使用,

content = open("try.html","r")

我得到了所需的输出。

这里只有输入用户名和密码才能访问example.net。尽管解析正确完成,但上面的代码没有打印任何内容。如何将会话 cookie 值添加到此代码?

【问题讨论】:

    标签: python session cookies web-scraping beautifulsoup


    【解决方案1】:

    你尝试过请求吗?

    可以在会话中保留 cookie。

    import requests
    s = requests.Session()
    s.post('https://example.net/users/101', data = {'username' : 'sup', 'password' : 'pass'})
    r = s.get("https://example.net/users/101")
    soup = BeautifulSoup(r.text)
    

    更多关于 requests.Session()

    http://docs.python-requests.org/en/latest/user/advanced/

    【讨论】:

    • 如何添加多个cookie?
    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多