注释import requestsurl = 'http://www.zhihu.com'headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}response = requests.get(url, headers=headers)print('状态码:', response.status_code)print('返回内容:', response.content.decode('utf-8'))
时间: 2023-07-14 19:13:59 浏览: 43
这段代码是使用 requests 库向知乎网站发送 GET 请求,并设置了请求头部(User-Agent),然后打印出响应的状态码和内容。其中,状态码表示服务器对请求的响应状态,200 表示成功,404 表示未找到页面等等;内容则是服务器返回的 HTML 页面内容。通过 decode('utf-8') 方法将字节流转换为字符串。
相关问题
import requestsurl = 'http://www.zhihu.com'headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}response = requests.get(url, headers=headers)print('状态码:', response.status_code)print('返回内容:', response.content.decode('utf-8'))
这是一个使用 Python 的 requests 库向知乎网站发送 HTTP GET 请求,并打印出响应状态码和内容的代码。其中,headers 参数是为了模拟浏览器访问而设置的请求头信息,防止被服务器拒绝访问。如果响应内容中有中文字符,则需要用 decode() 方法将其转换为 Unicode 编码。
import requests from bs4 import BeautifulSoup # 登录知乎账号,获取 cookie login 使用以上代码url = 'https://www.zhihu.com/signin' login_data = { 'username': 'your_username', 'password': 'your_password', } headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} session = requests.Session() session.post(login_url, headers=headers, data=login_data) # 访问知乎付费内容页面,使用登录后的 cookie url = 'https://www.zhihu.com/question/xxx/answer/xxx' response = session.get(url, headers=headers) html = response.text soup = BeautifulSoup(html, 'html.parser') content = soup.find('div', class_='RichContent') print(content.text)
这段代码的作用是使用 Python 的 requests 库和 BeautifulSoup 库模拟登录知乎账号,并获取知乎付费内容页面的内容。首先定义了登录知乎账号需要的用户名和密码,以及请求头部信息。然后创建一个会话 session,调用 post 方法模拟登录,并将登录后的 session 保存下来。接着访问知乎付费内容页面,使用登录后的 session 和请求头部信息,调用 get 方法获取页面 HTML,然后使用 BeautifulSoup 库解析 HTML,并找到页面中的付费内容。最后打印出付费内容的文本信息。注意,这段代码中的 xxx 需要替换为实际的知乎问题 ID 和答案 ID。