【问题标题】:Trying to scrape the web from a web page from a separate tab I opened up with selenium试图从我用 selenium 打开的单独选项卡中的网页中抓取网页
【发布时间】:2020-04-14 18:47:02
【问题描述】:

我能够使用 selenium 在我的 Chrome 网络浏览器的单独选项卡中打开一个网页。这个网页有一个庞大的表格数据,我想通过beautifulsoup 获取。但是,我的代码生成了以下错误消息。我的代码正在 Windows 上运行。

selenium.common.exceptions.NoSuchWindowException: Message: no such window: target window already closed
from unknown error: web view not found

以下是我一直在使用的代码。

从硒导入网络驱动程序 从 bs4 导入 BeautifulSoup 将熊猫导入为 pd 导入请求 导入操作系统 进口时间

#Open Webpage
url = "https://www.example.com"
driver=webdriver.Chrome(executable_path=r"C:\Users\Ben Lutz\Desktop\Ben Lutz\Runway Data Project\Updated Data\New Sheets\Scripts\chromedriver.exe")
driver.get(url)

driver.find_element_by_partial_link_text('Run').click()
time.sleep(100)
driver.close()

#Scrape Data
df_url = driver.current_url #This is the part of the code that the error is highlighting
page = requests.get(df_url).text
soup = BeautifulSoup(page, features = 'lxml')
text = soup.get_text()
soup.prettify()

table = soup.find('table')
table_rows = table.find_all('tr')
#print(table_rows)

Operations = pd.DataFrame()
for tr in table_rows:
    td = tr.find_all('td')
    row = [i.text for i in td]
    df_row = pd.DataFrame(row).T
    Operations = Operations.append(df_row.iloc[0])
print(Operations.head)

我产生这个错误是有原因的吗?应该如何解决这个困境?

任何帮助都是真正有帮助的。谢谢。

【问题讨论】:

    标签: python python-3.x selenium beautifulsoup


    【解决方案1】:

    您收到错误是因为您调用了driver.close(),然后引用了driver.current_url。调用close 后,浏览器窗口关闭,因此没有浏览器窗口可以访问当前 URL。

    df_url = driver.current_url 移到driver.close() 行上方,您应该可以开始了。

    【讨论】:

      【解决方案2】:

      您已经关闭了浏览器,这是您遇到问题的原因。删除驱动程序。从导致问题的代码中关闭(),然后尝试

      driver. close() 命令用于关闭当前具有焦点的浏览器窗口。

      【讨论】:

        猜你喜欢
        • 2019-06-19
        • 2015-07-10
        • 1970-01-01
        • 1970-01-01
        • 2021-05-29
        • 1970-01-01
        • 2021-07-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多