简体   繁体   中英

How to handle drop down list with div tag and multiple attributes?

I am trying to automate the location selection process, however I am struggle with it. So for, I can only open the menu and select the first item. And my code is:

import bs4
from bs4 import BeautifulSoup
import selenium
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome(ChromeDriverManager().install())
url = 'https://www.ebay.com/b/Food-Beverages/14308/bn_1642947?listingOnly=1&rt=nc'
driver.get(url)
soup = BeautifulSoup(driver.page_source, 'html.parser')
button = driver.find_element_by_id('gh-shipto-click') //find the location button
button.click()
button2 = driver.find_element_by_id('gh-shipto-click-body-cnt') //open the menu
button2.click()
driver.find_element(By.XPATH,"//div[@role='menuitemradio']").click() //choose the first location

I believe the attribute "data-makeup-index" (show in the pic) would help, but I don't know how to use it.

Sine some of you may not able to find the "ship to" button. Here is the html code I copied from the web.

<li id="gh-shipto-click" class="gh-eb-li">
<div class="gh-menu">
<button _sp="m570.l46241" title="Ship to" class="gh-eb-li-a gh-icon" aria-expanded="false" aria-controls="gh-shipto-click-o" aria-label="Ship to Afghanistan"><i class="flgspr gh-flag-bg flaaf"></i><span>Ship to</span></button>
<i class="flgspr gh-flag-bg flaaf"></i>

在此处输入图片说明

在此处输入图片说明

“运送到”按钮 html

我找到了我的答案如下:

driver.find_element(By.XPATH,"//div[@role='menuitemradio'][{an integer}]").click()

Although the Ship to was not visible to my location, I've inspected it from different Geo location and guess what I was able to find this element style="display: none;
I've removed the none temporarily, and it got displayed.

<li id="gh-shipto-click" class="gh-eb-li gh-modal-active" style="display:none;" aria-hidden="false">

 You could find the element by these XPath and handle the dropdown

 #This XPath is taking you to the specific div where you need to provide the element index [1][2][3] the ID of this XPath is dynamic
 driver.find_element_by_xpath("((((//*[contains(@id,'nid-')])[2])//child::div/div")


 driver.find_element_by_xpath("//*[@class='cn']")

I know you got your solution, but this what I've tried It might help

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM