如何使用硒在抓取前从一个网址标签转到另一个网址标签?

时间:2020-04-15 19:43:45

标签: python python-3.x selenium beautifulsoup

我创建了以下代码,希望通过几个参数打开一个新选项卡,然后抓取新选项卡上的数据表。

#Open Webpage
url = "https://www.website.com"
driver=webdriver.Chrome(executable_path=r"C:\mypathto\chromedriver.exe")
driver.get(url)

#Click Necessary Parameters
driver.find_element_by_partial_link_text('Output').click()
driver.find_element_by_xpath('//*[@id="flexOpt"]/table/tbody/tr/td[2]/input[3]').click()
driver.find_element_by_xpath('//*[@id="flexOpt"]/table/tbody/tr/td[2]/input[4]').click()
driver.find_element_by_xpath('//*[@id="repOpt"]/table[2]/tbody/tr/td[2]/input[4]').click()
time.sleep(2)

driver.find_element_by_partial_link_text('Dates').click()
driver.find_element_by_xpath('//*[@id="RangeOption"]').click()
driver.find_element_by_xpath('//*[@id="Range"]/table/tbody/tr[1]/td[2]/select/option[2]').click()
driver.find_element_by_xpath('//*[@id="Range"]/table/tbody/tr[1]/td[3]/select/option[1]').click()
driver.find_element_by_xpath('//*[@id="Range"]/table/tbody/tr[1]/td[4]/select/option[1]').click()
driver.find_element_by_xpath('//*[@id="Range"]/table/tbody/tr[2]/td[2]/select/option[2]').click()
driver.find_element_by_xpath('//*[@id="Range"]/table/tbody/tr[2]/td[3]/select/option[31]').click()
driver.find_element_by_xpath('//*[@id="Range"]/table/tbody/tr[2]/td[4]/select/option[1]').click()
time.sleep(2)

driver.find_element_by_partial_link_text('Groupings').click()
driver.find_element_by_xpath('//*[@id="availFld_DATE"]/a/img').click()
driver.find_element_by_xpath('//*[@id="availFld_LOCID"]/a/img').click()
driver.find_element_by_xpath('//*[@id="availFld_STATE"]/a/img').click()
driver.find_element_by_xpath('//*[@id="availFld_DDSO_SA"]/a/img').click()
driver.find_element_by_xpath('//*[@id="availFld_CLASS_ID"]/a/img').click()
driver.find_element_by_xpath('//*[@id="availFld_REGION"]/a/img').click()
time.sleep(2)

driver.find_element_by_partial_link_text('Run').click()
time.sleep(2)

df_url = driver.switch_to_window(driver.window_handles[0])
page = requests.get(df_url).text
soup = BeautifulSoup(page, features = 'html5lib')
soup.prettify()

但是,当我运行它时,会弹出以下错误消息。

requests.exceptions.MissingSchema: Invalid URL 'None': No schema supplied. Perhaps you meant http://None?

我会说,无论使用什么参数,新选项卡始终生成相同的URL。换句话说,如果新选项卡创建了www.website.com/b,则无论更改参数如何,它也会在第三,第四等时间创建www.website.com/b。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

问题出在这里:

df_url = driver.switch_to_window(driver.window_handles[0])
page = requests.get(df_url).text

df_url未引用页面的URL。为此,您应在切换窗口后调用driver.current_url以获取活动窗口的网址。

其他一些指针:

  • 通过xpath查找元素效率相对较低(source
  • 您可以使用explicit waits代替time.sleep

答案 1 :(得分:0)

在驱动程序变量下面插入网址,因为首先执行webdriver,然后执行提供的网址

driver=webdriver.Chrome(executable_path=r"C:\mypathto\chromedriver.exe")
url = "https://www.website.com"