【问题标题】:Selenium: How to parse through a code after using selenium to click a dropdownSelenium:如何在使用 selenium 单击下拉列表后解析代码
【发布时间】:2019-03-10 00:56:07
【问题描述】:

我正在尝试通过此网页https://www.sigmaaldrich.com/ 进行网络抓取。到目前为止,我已经实现了代码使用请求方法来使用搜索栏。之后,我想寻找化合物的不同价格。在单击价格下拉菜单之前,包含价格的 html 代码不可见。我通过使用 selenium 单击所需类的所有下拉菜单来实现这一点。但是在那之后,我不知道如何获取点击下拉菜单后生成的网页的html代码以及价格放置在哪里。

到目前为止,这是我的代码:

import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep

#get the desired search terms by imput

 name=input("Reagent: ")
 CAS=input("CAS: ")

  #search using the name of the compound

  data_name= {'term':name, 'interface':'Product%20Name', 'N':'0+',
       'mode':'mode%20matchpartialmax', 'lang':'es','region':'ES',
        'focus':'product', 'N':'0%20220003048%20219853286%20219853112'}
   #search using the CAS of the compound

   data_CAS={'term':CAS, 'interface':'CAS%20No.', 'N':'0','mode':'partialmax',
        'lang':'es', 'region':'ES', 'focus':'product'}
#get the link of the name search
 r=requests.post("https://www.sigmaaldrich.com/catalog/search/",    params=data_name.items())

 #get the link of the CAS search
n=requests.post("https://www.sigmaaldrich.com/catalog/search/",    params=data_CAS.items())

#use selenium to click in the dropdown(only for the name search)

driver=webdriver.Chrome(executable_path=r"C:\webdrivers\chromedriver.exe")
driver.get(r.url)
dropdown=driver.find_elements_by_class_name("expandArrow")
for arrow in dropdown:
    arrow.click()

正如我所说,在此之后,我需要在打开下拉列表后找到一种获取 html 代码的方法,以便我可以查找价格类。我尝试了不同的方法,但似乎没有得到任何可行的解决方案。

感谢您的帮助。

【问题讨论】:

  • 到目前为止,您尝试了哪些不同的东西来提取价格?向我们展示您的代码 sn-p 和 html 代码。

标签: python selenium web-scraping


【解决方案1】:

您可以尝试使用 Selenium WebDriverWait。 WebDriverWait

WebDriverWait wait = new WebDriverWait(driver, 30);

WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(css));

【讨论】:

  • 你是对的!!使用 selenium 实现自动化的最佳方法是使用 WebDriverWait,但他的问题是关于如何获取所有 HTML 代码......因此我的答案......
【解决方案2】:

首先,您应该使用奥斯汀指出的 WebDriverWait。

对于你的问题,试试这个:

from selenium import webdriver


driver=webdriver.Chrome(executable_path=r"C:\webdrivers\chromedriver.exe")
driver.get(r.url)
dropdown=driver.find_elements_by_class_name("expandArrow")
for arrow in dropdown:
    arrow.click()
    html_source = driver.page_source
    print(html_source)

希望对你有帮助!

【讨论】:

  • 谢谢,这已经奏效了,我已经尝试使用 sleep 而不是 WebDriverWait 函数,因为我还不知道如何使用它(我目前正在研究它)并且我已经得到了效果不错。
  • ? 很高兴为您提供帮助!你真的应该使用 webdriverwait!
猜你喜欢
  • 1970-01-01
  • 2018-08-02
  • 2013-08-05
  • 1970-01-01
  • 1970-01-01
  • 2021-03-07
  • 1970-01-01
  • 2023-04-09
  • 2021-03-10
相关资源
最近更新 更多