【问题标题】:How can I scrape this?我怎么能刮这个?
【发布时间】:2015-10-07 06:04:55
【问题描述】:

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

【问题讨论】:

  • 一个选项是使用scrapy link。为了使表单提交可以参考link
  • 请阅读指南How do I ask a good question,尤其是关于最小、完整和可验证示例(MCVE)的部分。这将帮助您自己解决问题。如果您这样做但仍然卡住,您可以回来发布您的 MCVE、您尝试了什么以及结果如何,以便我们更好地帮助您。

标签: python selenium web-scraping mechanize robobrowser


【解决方案1】:

您可以在 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 表单下的所有可用下拉选项以显示所有数据。

希望有帮助!

【讨论】:

  • 谢谢!当您调用 browser.get(url) 时,Selenium 会打开一个窗口吗?我只是好奇。
  • 会的。但是,如果您想在一切正常运行后隐藏浏览器,则几乎没有办法解决这个问题。一种选择是使用无头网络驱动程序,例如 PhantomJS。我还阅读了有关使用虚拟显示模块为 webdriver 设置虚拟显示以在其中运行的信息。可以在此处找到有关此选项和其他选项的更多信息:stackoverflow.com/questions/16180428/…>.
猜你喜欢
  • 2010-11-21
  • 2018-08-29
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多