gpt4 book ai didi

Python网络爬虫,通过链接爬取并找到特定的词

转载 作者:行者123 更新时间:2023-11-28 19:13:14 25 4
gpt4 key购买 nike

所以我正在尝试编写一个网络爬虫程序,该网络爬虫程序进入雕像标题的每一章,并计算其内容中一组关键词(“应该”、“必须”)的出现次数。

下面是我用来获取每个章节链接的代码。我使用的基本 URL 是 http://law.justia.com/codes/georgia/2015/

import requests
from bs4 import BeautifulSoup, SoupStrainer
import re
from collections import Counter

pattern1 = re.compile(r"\bshall\b",re.IGNORECASE)
pattern2 = re.compile(r"\bmust\b",re.IGNORECASE)


########################################Sections##########################
def levelthree(item2_url):
r = requests.get(item2_url)
for sectionlinks in BeautifulSoup((r.content),"html.parser",parse_only=SoupStrainer('a')):
if sectionlinks.has_attr('href'):
if 'section' in sectionlinks['href']:
href = "http://law.justia.com" + sectionlinks.get('href')
href = "\n" + str(href)
print (href)



########################################Chapters##########################
def leveltwo(item_url):
r = requests.get(item_url)
for sublinks in BeautifulSoup((r.content), "html.parser", parse_only=SoupStrainer('a')):
if sublinks.has_attr('href'):
if 'chapt' in sublinks['href']:
chapterlinks = "http://law.justia.com" + sublinks.get('href')
# chapterlinks = "\n" + str(chapterlinks)
#print (chapterlinks)


######################################Titles###############################
def levelone(url):
r = requests.get(url)
for links in BeautifulSoup((r.content), "html.parser", parse_only=SoupStrainer('a')):
if links.has_attr('href'):
if 'title-43' in links['href']:
titlelinks = "http://law.justia.com" + links.get('href')
# titlelinks = "\n" + str(titlelinks)
leveltwo(titlelinks)
# print (titlelinks)


###########################################################################
base_url = "http://law.justia.com/codes/georgia/2015/"
levelone(base_url)

问题是页面的结构通常是标题-章节-章节-内容(例如:http://law.justia.com/codes/georgia/2015/title-43/chapter-1/section-43-1-1/)

但有些是标题 - 章节 - 文章 - 部分 - 内容(例如 http://law.justia.com/codes/georgia/2015/title-43/chapter-4/article-1/section-43-4-1/ )

我能够获得第一个场景的链接。但是,我会错过所有的标题-章节-文章-章节-内容

我的问题是,我该如何编码才能获得每一章的内容(从章节链接和从文章到章节的链接),然后查找单词的出现(例如“shall”或“must” ") 每章单独?

我想按章节查找词频,希望输出是这样的

第一章

Word     Frequency
shall 35
must 3

第 2 章

Word     Frequency
shall 59
must 14

最佳答案

对于这个问题,计算url中的'/'

http://law.justia.com/codes/georgia/2015/title-43/chapter-1/section-43-1-1/ ) http://law.justia.com/codes/georgia/2015/title-43/chapter-4/article-1/section-43-4-1/ )

if url.count('/') == 9:
# do somthing
if url.count('/') == 10:
# do somthing

或者你可以做一个简单的技巧:

part = url.split('/')
title = part[7]
chapter = part[8]
section = part[-1]

注:-1表示最后一部分

计数应或必须:

同样使用计数函数

shall_count = response_text.count('shall')
must_count = response_text.count('must')

关于Python网络爬虫,通过链接爬取并找到特定的词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37306370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com