【python爬虫】利用selenium获取百度搜索结果及标红的相关关键字

一、环境搭建

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/ 文件夹下面。

二、获取搜索结果及标红的相关关键字

【python爬虫】利用selenium获取百度搜索结果及标红的相关关键字_第1张图片

使用如下代码: 

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

你可能感兴趣的:(爬虫)