我正在尝试填写 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
, Risk3Intermediate
和 Risk3High
分别。此外"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/