如何使用Selenium定位包含文本的按钮?

时间:2018-11-23 14:48:33

标签: selenium web-scraping beautifulsoup

我需要的:在Chrome应用商店中的扩展程序描述(例如this one)中切换到Reviews标签,以计算评论数。

我所做的事情:使用BeautifulSoup + Selenium在标签之间切换。我使用了driver.find_element_by_id('id') BUT ,它返回了一个找不到元素的错误。

这是我使用的代码:

    from selenium import webdriver
    driver = webdriver.Chrome()
    driver.get(url)
    button = driver.find_element_by_id(':22')
    button.click()
    page = requests.get(driver.current_url)
    soup = BeautifulSoup(page.content,'html5lib')
    comment_list = soup.find('div', class_ = 'e-f-b-L') #the class of reviews I need to count.

这是Review按钮元素的html代码:

enter image description here

问题:

如何使其单击“审阅”按钮,以便显示“审阅”选项卡?

1 个答案:

答案 0 :(得分:1)

如果您定义了一个简单的xpath,例如Reviews,则可以非常平滑地单击该'//div[.="Reviews"]'选项卡。查看脚本作为概念证明:

from selenium import webdriver
from selenium.webdriver.support import ui

url = "https://chrome.google.com/webstore/detail/emoji-keyboard-by-emojion/ipdjnhgkpapgippgcgkfcbpdpcgifncb?hl=en"

driver = webdriver.Chrome()
wait = ui.WebDriverWait(driver, 10)
driver.get(url)
wait.until(lambda driver: driver.find_element_by_xpath('//div[.="Reviews"]')).click()
driver.quit()

使其变得无头:

from selenium import webdriver
from selenium.webdriver.support import ui

url = "https://chrome.google.com/webstore/detail/emoji-keyboard-by-emojion/ipdjnhgkpapgippgcgkfcbpdpcgifncb?hl=en"

chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_argument("--headless")
driver = webdriver.Chrome(chrome_options=chromeOptions)
wait = ui.WebDriverWait(driver, 10)
driver.get(url)
wait.until(lambda driver: driver.find_element_by_xpath('//div[.="Reviews"]')).click()
print("It's done")