合并Beautifulsoup和机械化以填写表格并从同一URL检索结果

时间:2019-05-03 21:04:20

标签: 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为'是'。

1 个答案:

答案 0 :(得分:0)

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

我希望这对您有帮助