Utilice Python para rastrear el conocimiento principal de una novela.

Hoy escribiré un artículo sobre el uso de Python para rastrear contenido en formato de texto de sitios web, aprenderlo y registrarlo.

Primero importe las bibliotecas de Python necesarias:

1. Abra cmd: ingrese: pip install request y presione Enter para descargar el paquete de solicitudes.

               ​ ​ ​ ​ ​ Ingrese: pip install bs4 y presione Enter para descargar el paquete bs4

Aquí he instalado los paquetes necesarios.

d50816cf4d7649489bddbd8e85398f28.png

2. Aquí rastreamos las siguientes URL:

url = "http://www.ibiqu.org/0_844/636719.html"  # 笔趣阁的斗破苍穹网址,这里只爬取一章

3. Encuentra tus propios encabezados

Abra cualquier página web del navegador, haga clic con el botón derecho del mouse, haga clic en inspeccionar, ingrese al modo de desarrollador y luego haga clic en Red

Aquí no vemos nada

af04eb9a37d34465a83e758eb528d2ee.png

Luego actualizamos la página.

7c6641409af64203bf9620a6b45899d7.png

Busque cualquiera en el atributo Nombre, busque User-Agent en los encabezados de la derecha y haga clic derecho para copiarlo.

5bc8249a8aac48eab2256c8179abad49.png

 

El siguiente es el código completo, todo con comentarios, solo necesitas cambiar el User-Agent para ejecutarlo directamente.

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"
#这里换成自己复制到的User-Agent即可
    }
# 爬取一章小说
import requests#导入requests库,用于获取网页内容
from bs4 import BeautifulSoup  # 从bs4库中导入BeautifulSoup

url = "http://www.ibiqu.org/0_844/636719.html"  # 笔趣阁的斗破苍穹网址,这里只爬取一章
# response = requests.get(url)
# headers 里面的参数内容是从百度里面找的,不然会被反爬虫
headers = {
    "user-agent": "这里写你复制到的User-Agent"
    }

response1 = requests.get(url, headers=headers)

# print(response1.text)

# 将文本数据转换成BeautifulSoup对象
# bs=BeautifulSoup(response1.content,"html5lib")#html5lib是解析器,需要pip install html5lib
bs = BeautifulSoup(response1.content, "html.parser")  # 同上

bs_find = bs.find('div', attrs={'id': 'content'})
# print(bs_find)
# print("\n")


book_list = bs_find.findAll('p')  # 查找所有的p标签
# print(book_list)#列表
# 遍历数据
# 写入数据
with open('斗破苍穹.txt', 'a', encoding='utf-8') as f:#打开文件,写入爬取的内容
    for txt in book_list:
        f.write(txt.text)
        f.write("\n")
print("写入完成")

 

 

おすすめ

転載: blog.csdn.net/weixin_46713492/article/details/131214099