python - 合并 Beautifulsoup 和 Mechanize 以填写表单并从同一 URL 检索结果

标签 python forms beautifulsoup mechanize

我正在尝试填写 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 为“Yes”。

最佳答案

使用 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']

其中最后三个元素是 Risk3Low , Risk3IntermediateRisk3High分别。此外"NA" = "No""1" = "Yes" .

这就是我使用 results_transform 的原因为了改造
['NA', 'NA', '1', 'NA', 'NA']

进入:
['No', 'No', 'Yes', 'No', 'No']

我希望这有帮助

关于python - 合并 Beautifulsoup 和 Mechanize 以填写表单并从同一 URL 检索结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55977101/

相关文章:

javascript - 编辑文本输入时,如何在没有表单的 onSubmit 处理程序的情况下执行特定的 JavaScript 操作以点击 "Enter"键?

python - 如何使用 BeautifulSoup 在网页中找到具有特定类的元素?

python - 当我不使用 BeautifulSoup 时如何摆脱 BeautifulSoup html 解析器错误

python - 通过 pandas read_html 获取 HTML 表将不起作用

python - 变量不会分配给 Python 中的输入

python - 连接到 pyqtSignal 的 lambda 中对象的生命周期

Javascript 复选框表单验证

forms - 是否会使用 HTML5 自动对焦将焦点设置为不可见的表单控件?

Python-值错误: sign must be an integer with the value 0 or 1

python - Python 中的 Watts 和 Strogatz 图