【问题标题】:Unable to Identify Webpage in BeautifulSoup by URL无法通过 URL 识别 BeautifulSoup 中的网页
【发布时间】:2017-05-23 06:07:48
【问题描述】:

我正在使用 Python 和 Selenium 来尝试从某个搜索页面的结果页面中抓取所有链接。 无论我在上一个屏幕中搜索什么,结果页面上任何搜索的 URL 都是:“https://chem.nlm.nih.gov/chemidplus/ProxyServlet” 如果我使用 Selenium 进行自动搜索,然后尝试将此 URL 读入 BeautifulSoup,我得到 HTTPError: HTTP Error 404: Not Found

这是我的代码:

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from urllib.request import urlopen
from bs4 import BeautifulSoup
import csv


# create a new Firefox session
driver = webdriver.Firefox()
# wait 3 seconds for the page to load
driver.implicitly_wait(3)

# navigate to ChemIDPlus Website
driver.get("https://chem.nlm.nih.gov/chemidplus/")
#implicit wait 10 seconds for drop-down menu to load
driver.implicitly_wait(10)

#open drop-down menu QV7 ("Route:")
select=Select(driver.find_element_by_name("QV7"))
#select "inhalation" in QV7
select.select_by_visible_text("inhalation")
#identify submit button

search="/html/body/div[2]/div/div[2]/div/div[2]/form/div[1]/div/span/button[1]"

#click submit button
driver.find_element_by_xpath(search).click()

#increase the number of results per page
select=Select(driver.find_element_by_id("selRowsPerPage"))
select.select_by_visible_text("25")
#wait 3 seconds
driver.implicitly_wait(3)

#identify current search page...HERE IS THE ERROR, I THINK
url1="https://chem.nlm.nih.gov/chemidplus/ProxyServlet"
page1=urlopen(url1)
#read the search page
soup=BeautifulSoup(page1.content, 'html.parser')

我怀疑这与代理服务器有关,Python 没有收到识别网站所需的信息,但我不确定如何解决这个问题。 提前致谢!

【问题讨论】:

    标签: python selenium proxy-server


    【解决方案1】:

    我使用 Selenium 来识别新的 URL,作为一种解决方法来识别正确的搜索页面: url1=driver.current_url 接下来,我使用 requests 来获取内容并将其提供给 beautifulsoup。 总之,我补充说:

    #Added to the top of the script
    import requests
    ...
    #identify the current search page with Selenium
    url1=driver.current_url
    #scrape the content of the results page
    r=requests.get(url)
    soup=BeautifulSoup(r.content, 'html.parser')
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-14
      • 2019-08-01
      • 1970-01-01
      • 2021-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-02
      相关资源
      最近更新 更多