python搭建一个免费爬取搜索引擎最新搜索干净的链接正文的http服务器笔记

python搭建一个免费爬取搜索引擎最新搜索干净的链接正文的http服务器笔记

800_auto

现在收费的网站也有提供搜索结果的api,但是他是收费的,那么我们能不能把我们平时能打开免费搜索的搜索引擎变成我们的数据提供方呢,答案肯定是能的。

我们先用python的requests库来直接访问搜索引擎的搜索url,看看能不能返回有用数据

import requests
import html
# 百度的链接
baidu_link = 'https://www.baidu.com/s?wd=ai%E6%8A%80%E6%9C%AF%E5%8F%91%E5%B1%95%E7%8E%B0%E7%8A%B6%E4%B8%8E%E6%9C%AA%E6%9D%A5%E8%B6%8B%E5%8A%BF'

# 发送请求并获取重定向后的URL
response = requests.get(baidu_link, allow_redirects=True)
response.encoding = 'utf-8'
# 检查响应的编码
print(response.encoding)

# 使用正确的编码进行解码
print(html.escape(response.content.decode(response.encoding)))

800_auto

直接跳出了百度的安全验证,看来识别出来是机器访问的,可能request的user agent会暴露自己,我们加上真实的useragent

import requests
import html
# 百度的链接
baidu_link = 'https://www.baidu.com/s?wd=ai%E6%8A%80%E6%9C%AF%E5%8F%91%E5%B1%95%E7%8E%B0%E7%8A%B6%E4%B8%8E%E6%9C%AA%E6%9D%A5%E8%B6%8B%E5%8A%BF'
# 定义一个真实的User-Agent头
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'



# 设置请求头
headers = {
    'User-Agent': user_agent
}


# 发送请求并获取重定向后的URL
response = requests.get(baidu_link, headers=headers)
response.encoding = 'utf-8'
# 检查响应的编码
print(response.encoding)

# 使用正确的编码进行解码
print(html.escape(response.content.decode(response.encoding)))

不行,还是被识别出来了,我们对比一下用requests请求和selenium

requests请求,不修改headers

800_auto

requests请求增加自定义header

800_auto

那么selenium呢,他发出的请求我们看看有啥不同:

800_auto

selenium的请求头多了这么多内容:

Accept-Language: en-US
Accept-Encoding: gzip, deflate, br
Sec-Fetch-Dest: document
Sec-Fetch-User: ?1
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/86.0.4240.111 Safari/537.36
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
Connection: keep-alive

即时requests请求加入这么多的头,百度还是能识别,毕竟搜索的时候还有点击产生的其他辅助验证,那么我们换种方式,用selenium

#!/usr/local/python3/bin/python3
# -*- coding: utf-8 -*
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
from bs4 import BeautifulSoup
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_argument("--headless")
chromeOptions.add_argument("--remote-debugging-port=9222")
chromeOptions.add_argument('--no-sandbox')
browser = webdriver.Chrome('/usr/bin/chromedriver',chrome_options=chromeOptions)

browser.get("https://www.baidu.com/")               #进入相关网站
#保存网站截屏图片   


browser.find_element_by_id('kw').send_keys('ai 发展前景 ',Keys.RETURN)  # 输入框
browser.find_element_by_id('su').click()  # 点击搜索按钮


try:
    sleep(1)
    # 等待<h3 class="c-title t t tts-title">标签出现
    # element = WebDriverWait(browser, 10).until(
    #     EC.presence_of_element_located((By.CSS_SELECTOR, "h3.c-title.t.tts-title"))
    # )
    # 获取网页内容
    html_content = browser.page_source
    
    # 使用BeautifulSoup解析网页内容
    soup = BeautifulSoup(html_content, 'html.parser')
    
    # 查找所有的<h3>标签
    h3_tags = soup.find_all('h3', class_='c-title t t tts-title')
    
    # 提取<a>链接和标题
    for h3 in h3_tags:
        a_tag = h3.find('a')
        if a_tag:
            link = a_tag['href']
            title = a_tag.get_text(strip=True)
            print(f'Link: {link}')
            print(f'Title: {title}')
            print('-' * 50)
    
    # 关闭WebDriver
    browser.quit()
    
    
finally:
    # 关闭浏览器
    browser.quit()

        
		

800_auto

这次成功了,看来还是selenium好用,直接能抓取我们要的搜索信息,然后我们要对搜索链接的内容进行文本清晰,返回我们需要的文本,这里推荐这个免费的jina.ai,直接将url放在后面就能返回markdown格式的干净正文,非常方便,点击打开链接。当然你可以使用其他的python提取正文工具,例如readability-lxml

pip install readability-lxml

import requests
from readability import Document

url = 'https://blog.bfw.wiki/biji_17135193964468750098.html'

response = requests.get(url)

doc = Document(response.text)

print('Title:', doc.title())
print('Summary:', doc.summary())

800_auto

再看看jinaai,直接url拼接,将你要抓取的url放在https://r.jina.ai/后面就能获取干净的正文

https://r.jina.ai/https://blog.bfw.wiki/biji_17135193964468750098.html

800_auto

最后一步将所有的代码整合一起,形成一个http服务,这样,只要输入关键词,就能从百度抓取搜索信息并提取干净的正文了。

点击查看全文

{{collectdata}}

网友评论