Selenium:使用Selenium单击下拉菜单后如何解析代码

时间:2018-10-04 15:05:38

标签: python selenium web-scraping

我正在尝试通过该网页https://www.sigmaaldrich.com/进行爬网。到目前为止,我已经实现了使用requests方法使用搜索栏的代码。之后,我想寻找化合物的不同价格。单击价格下拉菜单后,包含价格的html代码才可见。通过使用硒单击所需类的所有下拉列表,我已经实现了这一点。但是在那之后,我不知道如何获取单击下拉列表后以及价格所在位置后生成的网页的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代码,以便我可以查找价格类。我尝试了不同的方法,但似乎没有任何有效的解决方案。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您可以尝试使用Selenium WebDriverWait。 WebDriverWait

WebDriverWait wait = new WebDriverWait(driver, 30);

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

答案 1 :(得分:0)

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

对于您的问题,请尝试以下操作:

{
    "@timestamp": "2018-10-04T12:24:48.930Z",
    "message": "Logging some data about my app",
    "level": "INFO"
}

希望这对您有帮助!