合并 Beautifulsoup 和 Mechanize 以填写表格并从相同的 URL 检索结果

Merge Beautifulsoup and Mechanize to fill a form and retrieve results from the same URL

我正在尝试使用多个值填写 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']

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

这就是为什么我使用 results_transform 来转换

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

进入:

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

希望对您有所帮助