凭借这5步,我30分钟学会了Python爬虫( 二 )


abstract = soup_post.find("h2", {"class": "article-intro"}).text现在,需要爬取帖子的全文内容 。如果已经理解了前面的内容,那么这部分会非常容易 。
该内容在article-text类的div内的多个段落(p标签)中 。

凭借这5步,我30分钟学会了Python爬虫

文章插图
 
BeautifulSoup可以通过以下一种方式提取完整的文本 。而不是遍历每个每个p标签、提取文本、然后将所有文本连接在一起 。
content = soup_post.find("div", {"class": "article-text"}).text下面,让我们把它们放在同一个函数内看一下:
def extract_post_data(post_url):soup_post = parse_url(post_url)title = soup_post.find("h1", {"class": "article-title"}).textdatetime = soup_post.find("header", {"class": "row sub-header"}).find("span")["datetime"]abstract = soup_post.find("h2", {"class": "article-intro"}).textcontent = soup_post.find("div", {"class": "article-text"}).textdata = https://www.isolves.com/it/cxkf/yy/Python/2020-12-10/{"title": title,"datetime": datetime,"abstract": abstract,"content": content,"url": post_url}return data提取多个页面上的帖子URL如果我们检查主页的源代码,会看到每个页面文章的标题:
凭借这5步,我30分钟学会了Python爬虫

文章插图
 
可以看到,每10篇文章出现在1个post-style1 col-md-6标签下:
下面,提取每个页面的文章就很容易了:
url = "https://www.premiumbeautynews.com/fr/marches-tendances/"soup = parse_url(url)section = soup.find("section", {"class": "content"})posts = section.findAll("div", {"class": "post-style1 col-md-6"})然后,对于每个单独的帖子,我们可以提取URL,该URL出现在h4标签内部 。
我们将使用此URL调用我们先前定义的函数extract_post_data 。
uri = post.find("h4").find("a")["href"]分页在给定页面上提取帖子后,需要转到下一页并重复相同的操作 。
如果查看分页,需要点击“下一个”按钮:
凭借这5步,我30分钟学会了Python爬虫

文章插图
 
到达最后一页后,此按钮变为无效 。
换句话说,当下一个按钮处于有效状态时,就需要执行爬虫操作,移至下一页并重复该操作 。当按钮变为无效状态时,该过程应停止 。
总结此逻辑,这将转换为以下代码:
next_button = ""posts_data = https://www.isolves.com/it/cxkf/yy/Python/2020-12-10/[]count = 1base_url = 'https://www.premiumbeautynews.com/'while next_button isnotNone:print(f"page number : {count}")soup = parse_url(url)section = soup.find("section", {"class": "content"})posts = section.findAll("div", {"class": "post-style1 col-md-6"})for post in tqdm_notebook(posts, leave=False):uri = post.find("h4").find("a")["href"]post_url = base_url + uridata = extract_post_data(post_url)posts_data.Append(data)next_button = soup.find("p", {"class": "pagination"}).find("span", {"class": "next"})if next_button isnotNone:url = base_url + next_button.find("a")["href"]count += 1【凭借这5步,我30分钟学会了Python爬虫】此循环完成后,将所有数据保存在posts_data中,可以将其转换为漂亮的DataFrames并导出为CSV或Excel文件 。
df = pd.DataFrame(posts_data)df.head()
凭借这5步,我30分钟学会了Python爬虫

文章插图
 
到这里,就把一个非结构化的网页转化成结构化的数据了!




推荐阅读