python爬虫類Beautiful Soup実戦

16569 ワード

前章ではbs 4の基本文法を紹介しましたが、今日は彼の実戦でページを解析します.
ブログの紹介
では今日はBeautiful Soupで同じ内容を取得します.両者の違い、xpathの解析を見てみましょう.https://blog.csdn.net/lovemenghaibin/article/details/82898280同じ解析を見てみましょう
from bs4 import BeautifulSoup
import requests
from lxml import etree

url = "https://blog.csdn.net/lovemenghaibin"

header = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"
}

response = requests.get(url, headers=header)

soup = BeautifulSoup(response.text, "lxml")

articles = soup.select(".article-item-box")
infos = []
for article in articles:
    title = article.select_one("a").get_text().replace(" ", "").strip()
    href_url = article.select_one("a")["href"]
    content = article.select_one("p[class=content] > a").get_text().strip()
    article_date = article.select_one(".info-box > p").get_text().strip()
    article_read = article.select(".info-box > p")[1].get_text().replace("   :","").strip()
    article_comment = article.select(".info-box > p")[2].get_text().replace("   :","").strip()
    info = {
        "title": title,
        "href": href_url,
        "content": content,
        "article_date": article_date,
        "article_read": article_read,
        "article_comment": article_comment
    }
    infos.append(info)
print(infos)

基本情報の取得

from bs4 import BeautifulSoup
import requests

url = "https://blog.csdn.net/lovemenghaibin"

header = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"
}

response = requests.get(url, headers=header)

soup = BeautifulSoup(response.text, "lxml")

home_url = soup.select_one("#uid")["href"]
name = soup.select_one("#uid").get_text()
profile = soup.select_one("#asideProfile")
article_count = soup.select("div .data-info dl")[0].select_one(".count").get_text()
fans = profile.select_one("#fanBox dd").get_text()
attentions = soup.select("div .data-info dl")[2].select_one("dd").get_text()
comment_count = soup.select("div .data-info dl")[3].select_one("dd").get_text()

blog_level = soup.select("div .grade-box dl")[0].select_one("a")["title"].split(",")[0]
read_total_count = soup.select("div .grade-box dl")[1].select_one("dd").get_text().strip()
point_count = soup.select("div .grade-box dl")[2].select_one("dd").get_text().strip()
rank = soup.select("div .grade-box dl")[3]["title"]

info = {
    "name": name,
    "home_url": home_url,
    "article_count": article_count,
    "fans": fans,
    "attentions": attentions,
    "comment_count": comment_count,

    "blog_level":blog_level,
    "read_total_count":read_total_count,
    "point_count":point_count,
    "rank":rank
}

小結
実はこの節と前回を比較することによって、beautiful soupの中で、その実用的な基本はcssセレクタで、私たちのこれらの基本的な操作を完成することができて、とても簡単で、内容の中から法則を探すのではありませんて、彼はドキュメントの構造に対してもっと少なくて、私たちはできるだけ属性によって探して、順序ではありません.ただし、識別可能なコンテンツが1つもない場合は、リストをcssで取り出し、n番目のラベルのコンテンツを取り出すしかありません.