我该怎么刮这个?

时间:2015-10-07 06:04:56

标签: python selenium web-scraping mechanize robobrowser

我需要抓取这个页面(有一个表单):http://kllads.kar.nic.in/MLAWise_reports.aspx,最好是Python(如果不是Python,那么JavaScript)。我正在寻找像RoboBrowser这样的库(基本上是Mechanize + BeautifulSoup)和(也许)Selenium但是我不太清楚如何去做。从检查元素来看,它似乎是我需要填写的WebForm。填写后,网页会生成一些我需要存储的数据。我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以在Selenium中相对轻松地与javascript网页表单进行交互。您可能需要快速安装Web驱动程序,但除此之外,您需要做的就是使用其xpath查找表单,然后让Selenium使用选项的xpath从下拉菜单中选择一个选项。对于提供的网页,看起来像这样:

#import functions from selenium module
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# open chrome browser using webdriver
path_to_chromedriver = '/Users/Michael/Downloads/chromedriver'
browser = webdriver.Chrome(executable_path=path_to_chromedriver)

# open web page using browser
browser.get('http://kllads.kar.nic.in/MLAWise_reports.aspx')

# wait for page to load then find 'Constituency Name' dropdown and select 'Aland (46)''
const_name = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="ddlconstname"]')))
browser.find_element_by_xpath('//*[@id="ddlconstname"]/option[2]').click()

# wait for the page to load then find 'Select Status' dropdown and select 'OnGoing'
sel_status = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="ddlstatus1"]')))
browser.find_element_by_xpath('//*[@id="ddlstatus1"]/option[2]').click()

# wait for browser to load then click 'Generate Report'
gen_report = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="BtnReport"]')))
browser.find_element_by_xpath('//*[@id="BtnReport"]').click()

在每次互动之间,您只是在尝试点击下一个元素之前给浏览器一些时间加载。填写完所有表单后,页面将根据所选选项显示数据,您应该能够刮取表格数据。尝试加载第一个选区名称选项的数据时,我遇到了一些问题,但其他问题似乎正常。

您还应该能够遍历每个网络表单下的所有下拉选项,以显示所有数据。

希望有所帮助!

相关问题