一、环境搭建
1. 安装chromedriver
brew cask install chromedriver
2. 安装selenium
pip3 install selenium
3. 安装beautifulsoup4
pip3 install beautifulsoup4
4. 用以下代码测试
from selenium import webdriver
driver = webdriver.Chrome() # 这里调用chrome浏览器
driver.get('https://www.baidu.com')
print(driver.title)
driver.quit()
5. 若报错
raise WebDriverException("Can not connect to the Service %s" % self.path) selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service /usr/local/bin/chromedriver
则有两种解决方法:
a)确保你的chromedriver在你的环境变量目录下
我的存放目录:/usr/local/bin/chromedriver
检查方式:terminal中输入which chromedriver
b)在缺失127.0.0.1 localhost的情况下,会出现Cannot connect to the service... 错误
检查方式:ping localhost
host存放目录: /private/etc/
使用vim修改即可。
6. 若报错chrome的版本不匹配
在浏览器地址栏中输入chrome://version/ 查看chrome版本
到chromedriver官网看对应版本、并下载对应的chromedriver驱动:https://sites.google.com/a/chromium.org/chromedriver/,下载到本地,解压到/usr/local/bin/ 文件夹下面。
使用如下代码:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import webdriverwait
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException
from bs4 import BeautifulSoup
browser_path = "/usr/local/bin/chromedriver"
browser = webdriver.Chrome(browser_path)
browser.get('https://www.baidu.com')
browser_input = browser.find_element_by_id('kw')
browser_input.clear()
query = “杨国福麻辣烫”
browser_input.send_keys(query)
browser_input.send_keys(Keys.RETURN)
ignored_exceptions = (NoSuchElementException, StaleElementReferenceException,)
try:
webdriverwait(browser, 10, ignored_exceptions=ignored_exceptions) \
.until(EC.title_contains(query))
except:
continue
# 使用BeautifulSoup解析搜索结果
bsobj = BeautifulSoup(browser.page_source, features="html.parser")
# 获取搜索结果队列
search_results = bsobj.find_all('div', {'class': 'result c-container'})
# 对于每一个搜索结果
for item in search_results:
# 获取每个搜索结果的标题的所有文本
text = search_item.h3.a.get_text(strip=True)
# 获取每个搜索结果的标题的标红关键字
keywords = search_item.h3.a.find_all('em')
# 获取每个搜索结果的摘要内容中的所有文本
# text = search_item.div.get_text(strip=True)
# 获取每个搜索结果的摘要内容中的标红关键字
# keywords = search_item.div.find_all('em')
print(text)
print(keywords)
browser.close()
参考网址:https://blog.csdn.net/Excaliburrr/article/details/79164163
https://blog.csdn.net/piglite/article/details/86352734
https://www.jianshu.com/p/cc45e1e15586
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。