Click on buttons with images

2019-07-30 14:20发布

I'm trying to crawl this page:

http://www.1800contractor.com/d.HI.html

I made this script

from selenium import webdriver


URL = "http://www.1800contractor.com/d.GA.html"
zip_codes = ['30324']

driver = webdriver.Firefox()
driver.get(URL)

zip_codes = ['30324']
text_box = driver.find_element_by_xpath('//*[@id="zip"]')
text_box.send_keys(zip_codes[0])        
button = driver.find_element_by_xpath('//*[@id="xmdListingsSearchForm"]')
button.click()

Basically I need to put a zip code in the search box:

zip_codes = ['30324']
text_box = driver.find_element_by_xpath('//*[@id="zip"]')
text_box.send_keys(zip_codes[0])

That part is working.

And then click in the 'Go' button:

button = driver.find_element_by_xpath('//*[@id="xmdListingsSearchForm"]')
button.click()

That part doesn't work, this is what I see at the html for that button:

<input type="image" src="/rfs/servicerequest/images/go_btn_grey_20x20.gif" height="20" width="20" style="position: relative; top: 1px;">

So I guess the problem is I'm not getting the reference to the actual button but a reference for the image of the button.

1条回答
干净又极端
2楼-- · 2019-07-30 14:28

There is a simpler way to solve it - send the newline character at the end of your ZIP code - it would automatically submit the form:

text_box.send_keys(zip_codes[0] + "\n")

Works for me.

If you insist on clicking the button/"button image", you can locate it using the following CSS selector matching a part of the src attribute value and trying to keep it readable:

driver.find_element_by_css_selector("input[src*=go_btn]").click()
查看更多
登录 后发表回答