Pythonクローラーbs4の基本的な使用法
免責事項:この記事の公開以降、この記事は参照用であり、複製またはコピーすることはできません。この記事を閲覧する当事者が国内法および規制の違反に関与している場合、すべての結果は、この記事を閲覧する当事者が負担し、この記事のブロガーとは関係ありません。また、この記事を閲覧する当事者の転載、コピー、その他の操作により、国内法および規制の違反によって引き起こされた紛争およびすべての結果は、この記事を閲覧する当事者が負担するものとし、この記事のブロガーとは関係ありません。
import requests
from bs4 import BeautifulSoup
1.bs4の基本構文
1.1htmlページを取得する
ローカルのhtmlページを取得する
# 读取文件
fp = open("./data/base/taobao.html", "r", encoding="UTF-8")
# 数据加载到该对象中 (本地的 html 文件)
html = BeautifulSoup(fp, "lxml")
print(html)
ウェブサイトを読んでhtmlページを取得する
# 爬取页面
response_text = requests.get(url="https://s.taobao.com/").text
# 数据加载到该对象中 (网络的 html 文件)
html = BeautifulSoup(response_text, "lxml")
print(html)
1.2タグを取得する
soup.<tagName>
デフォルトでは最初のもので、そのようなラベルがない場合はNoneを返します
print(html.a)
print(html.img)
print(html.input)
soup.find(<tagName>)
soup。<tagName>のデフォルトが最初に相当します
print(html.find("a"))
print(html.find("img"))
print(html.find("input"))
soup.find(<tagName>, <tagName.class>)
<tagName.class>を含むタグ属性の配置を検索できます
print(html.find("div", class_="site-nav"))
soup.find_all(<tagName>)
すべてのタグ、戻り値はリストです
print(html.find_all("a"))
print(html.find_all("input"))
soup.select(<select>)
クラスセレクターを使用してタグ、すべてのタグを検索します。戻り値はリストです。
print(html.select(".bang"))
print(html.select("#J_SearchForm .search-button"))
print(html.select(".copyright"))
1.3ラベルのコンテンツを取得する
text/get_text()
:すべてのコンテンツを
string
取得直接コンテンツを取得
print(html.find("div", class_="search-button").text)
print(html.find("div", class_="search-button").string)
print(html.find("div", class_="search-button").get_text())
1.4ラベルの属性を取得する
[<attribute>]
print(html.a["href"])
print(html.find("div")["class"])
print(html.find_all("div")[5]["class"])
2.例
スリーキングダムズの記事の内容
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import requests
from bs4 import BeautifulSoup
if __name__ == '__main__':
# url, UA, 参数
url = "https://www.shicimingju.com/book/sanguoyanyi.html"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0"
}
# 爬取页面
html = requests.get(url=url, headers=headers, timeout=5).text
# 数据加载到该对象中 (网络的 html 文件)
soup = BeautifulSoup(html, "lxml")
# 得到想要的标签 (含有章节的)
content = soup.select("div.book-mulu > ul > li > a")
# 文件
fp = open("./data/sgyy/sgyy.txt", "w", encoding="utf-8")
fp.write("章节\t链接\t内容\n")
for c in content:
# 爬取章节详细叙述的内容
href_text = requests.get(url="https://www.shicimingju.com" + c["href"], headers=headers, timeout=5).text
# 添加章节详细叙述的内容
href_soup = BeautifulSoup(href_text, "lxml")
href_text = href_soup.find("div", class_="chapter_content").text
# 添加章节的名称, 链接, 内容.
fp.write(f'{c.text}\t{"https://www.shicimingju.com" + c["href"]}\t{href_text}\n')
print(c.text + " 添加完成")
fp.close()