我打开了一个网页并使用 webdriver 代码登录。为此使用 webdriver,因为在我设置为抓取之前,该页面需要登录和各种其他操作。
目的是从这个打开的页面中抓取数据。需要找到链接并打开,所以selenium webdriver和BeautifulSoup会有很多的结合。
我查看了 bs4 的文档,BeautifulSoup(open("ccc.html"))
抛出错误
soup = bs4.BeautifulSoup(open("https://m/search.mp?ss=Pr+Dn+Ts"))
OSError: [Errno 22] Invalid argument: 'https://m/search.mp?ss=Pr+Dn+Ts'
我认为这是因为它不是 .html
?
最佳答案
您正在尝试通过网址打开页面。 open()
不会这样做,使用 urlopen()
:
from urllib.request import urlopen # Python 3
# from urllib2 import urlopen # Python 2
url = "your target url here"
soup = bs4.BeautifulSoup(urlopen(url), "html.parser")
或者,为人类使用 HTTP - requests
library :
import requests
response = requests.get(url)
soup = bs4.BeautifulSoup(response.content, "html.parser")
另请注意,强烈建议使用 specify a parser explicitly - 在这种情况下,我使用了 html.parser
,还有其他可用的解析器。
I want to use the exact same page(same instance)
一个常见的方法是获取 driver.page_source
并将其传递给 BeautifulSoup
进行进一步解析:
from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Firefox()
driver.get(url)
# wait for page to load..
source = driver.page_source
driver.quit() # remove this line to leave the browser open
soup = BeautifulSoup(source, "html.parser")
关于python - 使用一个已经打开的网页(带 Selenium )到 beautifulsoup?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41811904/