【问题标题】:Merge Beautifulsoup and Mechanize to fill a form and retrieve results from the same URL合并 Beautifulsoup 和 Mechanize 以填写表单并从同一 URL 检索结果
【发布时间】:2019-09-22 10:20:23
【问题描述】:

我正在尝试用多个值填写https://www.cancer.duke.edu/Nomogram/firstlinechemotherapy.html 上的表格并获得结果。请注意,URL 在提交时不会更改。 (验证按钮)

我尝试使用 Mechanize 填写表格并使用 Beautifulsoup 提取结果。但是由于 URL 永远不会改变,所以我无法接受响应。

import urllib.request
from urllib.request import urlopen
from bs4 import BeautifulSoup as bsoup
import mechanize

#Fill form with mechanize
br = mechanize.Browser()
br.open("https://www.cancer.duke.edu/Nomogram/firstlinechemotherapy.html")
response = br.response()
mech=response.read()
br.select_form(id='myform')
br.form['alb']='7'
br.form['hemo']='17'
br.form['alkph']='5000'
br.form['psa']='5000'
br.submit()

#Extract Output
url = urllib.request.urlopen("https://www.cancer.duke.edu/Nomogram/firstlinechemotherapy.html")
content = url.read()
soup= bsoup(content,"html.parser")
riskValue=soup.find('div',{'id':'resultPanelRisk3'})
tableValue=riskValue.find('table')
trValue=tableValue.find_all('tr')[1]
LowValue=trValue.find('td',{'id':'Risk3Low'}).string
IntermediateValue=trValue.find('td',{'id':'Risk3Intermediate'}).string
HighValue=trValue.find('td',{'id':'Risk3High'}).string

在上述代码中,LowValue 的值为“*”,而上述表单值的预期 LowValue 为“是”。

【问题讨论】:

  • 看起来您没有解析 br 对象的输出,机械?所以无论你的 br 输出是什么,在你的下一个代码块中你都没有使用它。据我所知,mechanize 和 urllib 不会自动与每个对话。还可以查看 requests 和 selenium,许多人在自动化浏览器或发送自定义标头方面拥有丰富的经验
  • 有没有办法让 mechanize 和 beautifulsoup 互相交谈?
  • 为什么不使用 RoboBrowser?

标签: python forms beautifulsoup mechanize


【解决方案1】:

使用requests library 这样做会更容易、更高效,因此您的代码应如下所示:

import requests

alb='7'
hemo='17'
alkph='5000'
psa='5000'

url = f"https://www.cancer.duke.edu/Nomogram/EquationServer?pred=1&risk=1&lnm=0&bm=0&visc=0&pain=0&ldh=0&psanew=0&alb={alb}&hemo={hemo}&alkph={alkph}&psa={psa}&equationName=90401&patientid=&comment=&_=1556956911136"
req = requests.get(url).text

results = req[req.index("Row6=")+5:].strip().split(",")
results_transform = ['Yes' if x == '1' else 'No' for x in results]

LowValue = results_transform[2] 
IntermediateValue= results_transform[3] 
HighValue= results_transform[4] 

PS:

results 变量输出如下内容:

['NA', 'NA', '1', 'NA', 'NA']

最后三个元素分别是Risk3LowRisk3IntermediateRisk3High。还有"NA" = "No""1" = "Yes"

这就是我使用results_transform 进行转换的原因

['NA', 'NA', '1', 'NA', 'NA']

进入:

['No', 'No', 'Yes', 'No', 'No']

希望对你有帮助

【讨论】:

  • 谢谢。这也有效。你能告诉我你是如何以及从哪里得到这个网址的吗?
  • @Prithvi 太棒了!我通过使用burp suite 拦截网站的流量获得了网址。那里有很多关于如何做到这一点的教程,它非常简单,不需要任何编码。如果您有任何其他问题,请随时提出!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-20
  • 1970-01-01
  • 2011-02-06
  • 2015-06-25
  • 2012-09-10
  • 1970-01-01
相关资源
最近更新 更多