python - 我怎么能刮这个?

标签 python selenium web-scraping mechanize robobrowser

我需要抓取这个页面(它有一个表格):http://kllads.kar.nic.in/MLAWise_reports.aspx ,最好使用 Python(如果不是 Python,则使用 JavaScript)。我在看像 RoboBrowser 这样的图书馆(基本上是 Mechanize + BeautifulSoup)和(也许)Selenium但我不太确定如何去做。通过检查元素,它似乎是我需要填写的 WebForm。填写后,网页会生成一些我需要存储的数据。我该怎么做?

最佳答案

您可以在 Selenium 中相对轻松地与 javascript web 表单交互。您可能需要快速安装 webdriver,但除此之外,您只需使用其 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()

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

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

希望有帮助!

关于python - 我怎么能刮这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32984862/

相关文章:

java - Selenium CSS 选择器

java - Selenium 测试日期输入时遇到问题,其中输入有最大和最小日期

java - 如何通过 FirefoxProfile 启动 Mozilla 浏览 session ?

java - 需要从 google 关键字外部工具中提取结果?

python - ". import certs"

java - 如何在Selenium中切换到子窗口的子窗口(窗口句柄和标题是动态的)?

python - 在 Python 中使用 pdfkit 将多个 html 文件转换为 pdf

Python 打开文件——你不需要文件的完整路径吗?

python - 如何将 python 模块从源安装到虚拟环境中

python - crontab - 随机运行命令