[英]Web Scraper for dynamic forms in python
我正在嘗試填寫此網站http://www.marutisuzuki.com/Maruti-Price.aspx的表格。
它由三個下拉列表組成。 一是汽車模型,二是州,三是城市。 前兩個是靜態的,第三個是city的,它是根據state的值動態生成的,正在運行一個onclick Java腳本事件,該事件獲取一個州中相應城市的值。
我熟悉python中的機械化模塊。 我遇到了幾個鏈接,這些鏈接告訴我我無法在機械化中處理動態內容 。 但是,“ 動態添加項目 ”部分中的鏈接http://toddhayton.com/2014/12/08/form-handling-with-mechanize-and-beautifulsoup/指出,我可以使用機械化來處理動態內容,但是我做到了不明白其中的這一行代碼
item = Item(br.form.find_control(name='searchAuxCountryID'),{'contents': '3', 'value': '3', 'label': 3})
此代碼行中與表單中的city字段對應的“ Item”是什么。 我遇到了硒模塊,它可以幫助我處理動態下拉列表。 但是我無法在其文檔中找到任何有關如何使用它的東西。
有人可以建議我如何針對不同的模型,州和城市提交此表格嗎? 任何有關如何解決此問題的鏈接將不勝感激。 python中有關如何提交表單的示例代碼將很有幫助。 提前致謝。
如果您在開發人員工具中查看發送到該站點的請求,則將看到在選擇狀態后立即發送了POST。 發送回的響應具有填寫城市下拉列表中的值的形式。
因此,要將其復制到腳本中,您需要以下內容:
看起來像:
#!/usr/bin/env python
import re
import mechanize
from bs4 import BeautifulSoup
def select_form(form):
return form.attrs.get('id', None) == 'form1'
def get_state_items(browser):
browser.select_form(predicate=select_form)
ctl = browser.form.find_control('ctl00$ContentPlaceHolder1$ddlState')
state_items = ctl.get_items()
return state_items[1:]
def get_city_items(browser):
browser.select_form(predicate=select_form)
ctl = browser.form.find_control('ctl00$ContentPlaceHolder1$ddlCity')
city_items = ctl.get_items()
return city_items[1:]
br = mechanize.Browser()
br.open('http://www.marutisuzuki.com/Maruti-Price.aspx')
br.select_form(predicate=select_form)
br.form['ctl00$ContentPlaceHolder1$ddlmodel'] = ['AK'] # model = Maruti Suzuki Alto K10
for state in get_state_items(br):
# 1 - Submit form for state.name to get cities for this state
br.select_form(predicate=select_form)
br.form['ctl00$ContentPlaceHolder1$ddlState'] = [ state.name ]
br.submit()
# 2 - Now the city dropdown is filled for state.name
for city in get_city_items(br):
br.select_form(predicate=select_form)
br.form['ctl00$ContentPlaceHolder1$ddlCity'] = [ city.name ]
br.submit()
s = BeautifulSoup(br.response().read())
t = s.find('table', id='ContentPlaceHolder1_dtDealer')
r = re.compile(r'^ContentPlaceHolder1_dtDealer_lblName_\d+$')
header_printed = False
for p in t.findAll('span', id=r):
tr = p.findParent('tr')
td = tr.findAll('td')
if header_printed is False:
str = '%s, %s' % (city.attrs['label'], state.attrs['label'])
print str
print '-' * len(str)
header_printed = True
print ' '.join(['%s' % x.text.strip() for x in td])
我在本教程中遇到了同樣的問題,這對我有用:
item = mechanize.Item(br.form.find_control(name='searchAuxCountryID'),{'contents': '3', 'value': '3', 'label': 3})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.