【问题标题】:how to read a POST request content with python如何使用 python 读取 POST 请求内容
【发布时间】:2019-07-21 05:13:17
【问题描述】:

嗨,当我尝试发送 POST 请求时,我得到了 200 个状态码,我可以读取 page.text,但是当我无法通过 xpath 查找元素时
抱歉英语不好

import requests
from lxml import html
cookies = {
    '_ga': 'GA1.2.2008948104.1563397982',
    'kfacommnet': 'f5e38c05-1e26-42ce-8794-afbded5e6ee1',
    'kfasession': '1rgbtjwd4dhjkbi3lyrwyzhk',
    'cookie_matching': 'true',
    'pushNotification-shownCount-2195': '15',
    'pushNotification-notWantPopUp-2195': 'true',
    'tlc': 'true',
    '_gid': 'GA1.2.109054603.1563596637',
}

headers = {
    'Origin': 'http://www.kanoon.ir',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'en-GB,en;q=0.9,fa-IR;q=0.8,fa;q=0.7,fr-CH;q=0.6,fr;q=0.5,en-US;q=0.4',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',
    'Content-Type': 'application/json; charset=UTF-8',
    'Accept': '*/*',
    'Referer': 'http://www.kanoon.ir/Public/SuperiorsRankBased?type=3',
    'X-Requested-With': 'XMLHttpRequest',
    'Connection': 'keep-alive',
}

data = '{"dept":"1","sahmieh":"2","rank":"345","reshte":null,"year":"97","univercity":null,"type":"3"}'
response = requests.post('http://www.kanoon.ir/Public/SuperiorsRankBasedShowSuperiors', headers=headers, cookies=cookies, data=data, verify=False)
page=response.text
tree = html.fromstring(page)
img = tree.xpath('//*[@id="header_area"]/div[1]/a/img')
print(img)

【问题讨论】:

  • 您遇到的错误是什么?找到元素了吗?您确定这是您要查找的元素的正确 XPATH 吗?
  • 您能否创建一个专注于该问题并包含示例输入和输出数据的示例?
  • 我什么都没有,我确定 XPATH 是正确的,我从 chrome 复制了它
  • 显示 response.text 以查看 HTML 并检查(在您的眼睛上)该元素是否存在于 HTML 中。或者您可能会在 HTML 中看到警告或错误消息。
  • 我试过代码,甚至没有tree.xpath('//img')。也许你必须到 get() 页面来获取新的 cookie。或者,您可能必须先登录此页面才能发布数据。

标签: python post web-scraping python-requests


【解决方案1】:

page=response.text 之后添加类似print(page) 的打印语句并检查打印语句的输出并通过查看输出来更正您的xpath。因为您指定的当前 xpath 不存在。

【讨论】:

  • response.text 应该没问题,因为他们正在使用html.fromstring() 创建tree
  • response.content 返回bytes 对象,而response.text 返回str 对象。
  • POST 请求有没有返回???你应该先检查状态response.status_code
猜你喜欢
  • 2020-09-27
  • 2018-05-27
  • 2019-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-08
相关资源
最近更新 更多