【问题标题】:Read page source before POST在 POST 之前读取页面源
【发布时间】:2017-06-14 12:08:35
【问题描述】:

我想知道是否有办法在阅读页面源后发布参数。例如:在发布 ID 之前阅读验证码#

我当前的代码:

import requests
id_number = "1"
url = "http://www.submitmyforum.com/page.php"
data = dict(id = id_number, name = 'Alex')
post = requests.post(url, data=data)

每次向http://submitforum.com/page.php 发出请求后都有一个可更改的验证码(obv 不是真实站点)我想读取该参数并将其提交给“数据”变量。

【问题讨论】:

  • 您是否想知道如何在加载此网页之前从网页中获取数据? 我觉得我错过了一个好的薛定谔猫笑话..
  • 您可以使用获取请求,解析页面源,获取验证码 ID/处理它,然后使用正确的验证码数据发送您的发布请求。但它并不总是有效,具体取决于所使用的验证码系统。为了这种目的,我终于结束了使用 webbrowser 仿真(例如:selenium python 实现),因为它可以用来保持相同的会话和类似的东西。 (正在做验证码安全分析和自动完成)
  • @Arount 我正在尝试读取网页源代码,以便获取一个可变值并将其添加到我的数据变量中。
  • @Retsim 你能详细说明一下吗?获取请求不会提供与发布请求不同的验证码吗?我假设在这种情况下我将执行 2 个请求?
  • @JeremyClaus 是的,在这种情况下您将执行 2 个请求,我看不到任何其他方式(即使模拟浏览器,您也需要两个)-我仍然可能是错的-,与发送任何内容之前一样,您需要先解析网页。这并不总是一个问题,因为一些验证码系统不会改变他们的挑战(基于 IP、基于时间、基于会话)并且会让您适应这一点。如果您的验证码不同(例如:Google reCaptcha),那么网络浏览器仿真是我所知道的最简单的方法,无需太多努力即可实现这一目标。

标签: python python-2.7 python-3.x web-scraping web-scripting


【解决方案1】:

正如OP cmets中所讨论的,可以使用selenium,也可能存在没有浏览器仿真的方法!

使用 Selenium (http://selenium-python.readthedocs.io/) 代替 requests 模块方法:

import re
import selenium
from selenium import webdriver

regexCaptcha = "k=.*&co="
url = "http://submitforum.com/page.php"

# Get to the URL
browser = webdriver.Chrome()
browser.get(url)

# Example for getting page elements (using css seletors)
# In this example, I'm getting the google recaptcha ID if present on the current page
try:
    element = browser.find_element_by_css_selector('iframe[src*="https://www.google.com/recaptcha/api2/anchor?k"]')
    captchaID = re.findall(regexCaptcha, element.get_attribute("src"))[0].replace("k=", "").replace("&co=", "")
    captchaFound = True
    print "Captcha found !", captchaID
except Exception, ex:
    print "No captcha found !"
    captchaFound = False

# Treat captcha
# --> Your treatment code

# Enter Captcha Response on page
captchResponse = browser.find_element_by_id('captcha-response')
captchResponse.send_keys(captcha_answer)

# Validate the form
validateButton = browser.find_element_by_id('submitButton')
validateButton.click()

# --> Analysis of returned page if needed

【讨论】:

  • 正是我想要的。谢谢朋友。
  • 很高兴它有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 2013-04-02
  • 2012-12-04
  • 2012-06-16
  • 2011-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多