【问题标题】:Can not scrape table after opening new web page tab打开新网页标签后无法抓取表格
【发布时间】:2020-04-16 21:40:23
【问题描述】:

我正在使用 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)

#scrape new web page
df_url = driver.switch_to_window(driver.window_handles[1])
df_url = driver.current_url
page = requests.get(df_url).text
soup = BeautifulSoup(page, features = 'html5lib')
print(soup.prettify())

但是,我得到的唯一 html 是以下...

<html><head></head><body></body></html>

这是有原因的吗?当我打开新标签时,我看到并用于抓取。我怎样才能让 python 读取我正在寻找的 html 部分?

【问题讨论】:

  • 表格是用javascript生成的吗?如果是这样,您将无法使用请求和 BS 来抓取它。
  • 点击次数过多,您应该在两次点击之间增加一些睡眠时间
  • 为什么要像这样结合 Selenium、requests 和 BeautifulSoup?

标签: python python-3.x selenium beautifulsoup


【解决方案1】:

不要使用请求,而是尝试将 page_source 保存为文本,以便美丽的汤进行解析。

#scrape new web page
df_url = driver.switch_to_window(driver.window_handles[1])
df_url = driver.current_url
page = driver.page_source
soup = BeautifulSoup(page, "lxml")
print(soup.prettify())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-11
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多