跟着我们一起学 Python 30天课程-第23天-网页爬虫
Web爬虫是通过爬虫从网站提取数据的技术或概念。它主要用于从网站收集有意义的数据,特别是在没有可用的API提取信息的情况下。今天,我探讨了使用Python进行网络抓取的基本知识,并希望分享我的经验。
抓取是一种脚本形式,它使我们能够自动化从网站中提取大型非结构化数据的过程,并以结构化方式对其进行组织,以将其用于多种目的,例如收集电子邮件,产品价格,股票价格,航班数据或任何其他相关信息信息。手动执行此类操作需要花费大量时间和精力。Python有一些了不起的库,使Web抓取相当容易且有趣。我主要浏览最基本和最受欢迎的图书馆Beautiful Soup,以熟悉该概念。
Good Practices
Web Scraping非常强大,关于它的用法有很多争论。大多数网站都有一个robots.txt
文件,其中提到应爬虫(爬虫)哪些特定URL,哪些不应该爬网。该文件主要是针对各种搜索引擎bot(例如google bot,yahoo bot,bing bot等)的指令,它们应该对哪些特定页面进行爬虫以优化搜索引擎。因此,所有搜索引擎抓取工具主要都是网络抓取工具,可从网站提取数据以按相关关键字对它们进行排名。但是,即使robots.txt
文件中不允许使用该网站,也不能从字面上限制Web抓取程序不抓取其数据。仔细检查网站的robots.txt
文件(如果存在)并从仅提及的URL中提取数据是一种很好的道德规范,以防止发生任何类型的数据泄露问题。
Scraping using Beautiful Soup
在今天的会议中,我决定尝试从Hacker News网站(开发人员社区中非常受欢迎的网站)中提取数据 。这些是robots.txt
文件中定义的规则
User-Agent: *
Disallow: /x?
Disallow: /vote?
Disallow: /reply?
Disallow: /submitted?
Disallow: /submitlink?
Disallow: /threads?
Crawl-delay: 30
因此,我们被允许从新闻页面https://news.ycombinator.com/newest抓取并获取数据,该页面列出了开发领域的最新文章。目标是抓取前5页并提取至少100点的文章及其链接。这对于自动获取所有高度投票的项目并从终端本身读取它们非常有用,而无需访问黑客新闻网站并手动搜索受欢迎的帖子。
首先需要安装两个库,requests
以便进行HTTP请求和beautifulsoup4
抓取网站。
pip install requests
pip install beautifulsoup4
hacker_news_scraper.py
import requests
from bs4 import BeautifulSoup
BASE_URL = 'https://news.ycombinator.com'
response = requests.get(BASE_URL)
# extract the text content of the web page
response_text = response.text
# parse HTML
soup = BeautifulSoup(response_text, 'html.parser')
print(soup.prettify()) # prints the html content in a readable format
https://www.crummy.com/software/BeautifulSoup/bs4/doc/上的 Beautiful Soup文档展示了各种用例。使用浏览器的检查元素工具,可以查看元素的选择器,然后将其用于提取数据。在这种情况下,所有文章都具有一个storylink
类,并且它们的关联点也具有该类score
。现在可以使用这些选择器来获取相应的数据并将其组合。
# extract all the links using the class selector
links_list = soup.select('.storylink')
# extract all the points using the class selector
points_list = soup.select('.score')
循环浏览链接后,可以将关联的标题,链接及其点合并为字典对象,然后附加到受欢迎的帖子列表中。
注意,该enumerate
函数用于获取每个元素的索引,以获取各个点,因为这些点不包含在链接容器中。
只有最低100分的帖子才会附加到热门列表中。
# loop though all links
for idx, link in enumerate(links_list):
# fetch the title of the post
post_title = link.get_text()
# fetch the link of the post
post_href = link.get('href')
# fetch the point text using the index of the link
# convert the point to integer
post_points = int(points_list[idx].get_text().replace(' points', ''))
# append to popular posts as a dictionary object if points is atleast 100
if post_points >= 100:
popular_posts.append(
{'title': post_title, 'link': post_href, 'points': post_points})
有一个有用的内置Python库pprint
,该库以更易读的格式在控制台中打印数据。
import pprint
然后可以用来查看热门列表
# loop though all links
for idx, link in enumerate(links_list):
# fetch the title of the post
post_title = link.get_text()
# fetch the link of the post
post_href = link.get('href')
# fetch the point text using the index of the link
# convert the point to integer
post_points = int(points_list[idx].get_text().replace(' points', ''))
# append to popular posts as a dictionary object if points is atleast 100
if post_points >= 100:
popular_posts.append(
{'title': post_title, 'link': post_href, 'points': post_points})
pprint.pprint(popular_posts) # prints in a readable format
上面的脚本仅从Hacker News的首页获取热门帖子。但是,根据期望的目标,我们需要从前五页或可能输入的任何页数中获取列表。因此,可以相应地修改脚本。
这是刮下流行列表的最终脚本。该代码也可以在Github存储库中找到https://github.com/arindamdawn/python-scripting
import requests
from bs4 import BeautifulSoup
import pprint
import time
BASE_URL = 'https://news.ycombinator.com'
# response = requests.get(BASE_URL)
def get_lists_and_points(soup):
# extract all the links using the class selector
links_list = soup.select('.storylink')
# extract all the points using the class selector
points_list = soup.select('.score')
return (links_list, points_list)
def parse_response(response):
# extract the text content of the web page
response_text = response.text
# parse HTML
soup = BeautifulSoup(response_text, 'html.parser')
return soup
def get_paginated_data(pages):
total_links_list = []
total_points_list = []
for page in range(pages):
URL = BASE_URL + f'?p={page+1}'
response = requests.get(URL)
soup = parse_response(response)
links_list, points_list = get_lists_and_points(soup)
for link in links_list:
total_links_list.append(link)
for point in points_list:
total_points_list.append(point)
# add 30 seconds delay as per hacker news robots.txt rules
time.sleep(30)
return (total_links_list, total_points_list)
def generate_popular_posts(links_list, points_list):
# create an empty popular posts list
popular_posts = []
# loop though all links
for idx, link in enumerate(links_list):
# fetch the title of the post
post_title = link.get_text()
# fetch the link of the post
post_href = link.get('href')
# fetch the point text using the index of the link
# convert the point to integer
# if points data is not available, assign it a default of 0
try:
post_points = int(
points_list[idx].get_text().replace(' points', ''))
except:
points_list = 0
# append to popular posts as a dictionary object if points is atleast 100
if post_points >= 100:
popular_posts.append(
{'title': post_title, 'link': post_href, 'points': post_points})
return popular_posts
def sort_posts_by_points(posts):
return sorted(posts, key=lambda x: x['points'], reverse=True)
def main():
total_links_list, total_points_list = get_paginated_data(5)
popular_posts = generate_popular_posts(total_links_list, total_points_list)
sorted_posts = sort_posts_by_points(popular_posts)
# print posts sorted by highest to lowest
pprint.pprint(sorted_posts)
if(__name__ == '__main__'):
main()
现在使用此脚本,我们甚至不需要访问Hacker News并搜索热门新闻。我们可以从控制台运行此脚本并获取最新消息。您可以根据自己的需要随意调整脚本并进行实验,或者尝试从自己喜欢的网站上抓取数据。
利用上述数据,我们可以做很多事情,例如
- 创建一个API以将其用于网站应用
- 用它来分析关键字趋势
- 创建新闻汇总网站等
Popular Scraping Libraries
当从网站抓取数据时,Beautiful Soup有其局限性。它使用起来非常简单,但是要从客户端呈现的复杂网站(基于角度的,基于React的网站)中抓取数据,则HTML标记在网站加载时将不可用。要从此类网站获取数据,可以使用更高级的库。这是一些流行的Python库和框架。
参考文献
- https://realpython.com/beautiful-soup-web-scraper-python/
- https://realpython.com/python-web-scraping-practical-introduction/
- https://www.digitalocean.com/community/tutorials/how-to-scrape-web-pages-with-beautiful-soup-and-python-3
Web爬虫是一个广阔的领域。使用美丽的汤,我们可能只是擦了一下表面。在这个领域中有很多可能性,我将在探索更多有关使用Python进行数据分析的同时进行探讨。希望我能够涵盖进一步探索所需的基本概念。
明天我将讨论使用Python进行Web开发的概念。
跟着我们一起学 Python 30天课程目录:
- 跟着我们一起学 Python 30天课程-第30天-免费Python资源
- 跟着我们一起学 Python 30天课程-第29天-自动化测试
- 跟着我们一起学 Python 30天课程-第28天-ML和数据科学II
- 跟着我们一起学 Python 30天课程-第27天-ML和数据科学I
- 跟着我们一起学 Python 30天课程-第26天-机器学习基础
- 跟着我们一起学 Python 30天课程-第25天-Web 开发进阶
- 跟着我们一起学 Python 30天课程-第24天-Web开发基础
- 跟着我们一起学 Python 30天课程-第23天-网页爬虫
- 跟着我们一起学 Python 30天课程-第22天-脚本额外功能Scripting Extras
- 跟着我们一起学 Python 30天课程-第21天-脚本编写基础
- 跟着我们一起学 Python 30天课程-第20天-调试和测试
- 跟着我们一起学 Python 30天课程-第19天-正则表达式
- 跟着我们一起学 Python 30天课程-第18天-文件I / O
- 跟着我们一起学 Python 30天课程-第17天-外部模块External Modules
- 跟着我们一起学 Python 30天课程-第16天-模块基础Module Basics
- 跟着我们一起学 Python 30天课程-第15天-生成器Generators
- 跟着我们一起学 Python 30天课程-第14天-错误处理Error Handling
- 跟着我们一起学 Python 30天课程-第13天-Decorators
- 跟着我们一起学 Python 30天课程-第12天-Lambda Expressions & Comprehensions
- 跟着我们一起学 Python 30天课程-第11天-函数编程Functional Programming基础
- 跟着我们一起学 Python 30天课程-第10天-OOP Missing Pieces
- 跟着我们一起学 Python 30天课程-第9天-OOP Pillars
- 跟着我们一起学 Python 30天课程-第8天-OOP基础知识
- 跟着我们一起学 Python 30天课程-第7天-开发环境搭建(Developer Environment)
- 跟着我们一起学 Python 30天课程-第6天-循环II和函数(Loops II & Functions)
- 跟着我们一起学 Python 30天课程-第5天-条件和循环I(Conditions & Loops I)
- 跟着我们一起学 Python 30天课程-第4天-数据类型III(Data Types III)
- 跟着我们一起学 Python 30天课程-第3天-数据类型II(Data Types II)
- 跟着我们一起学 Python 30天课程-第2天-数据类型I(Data Types I)
- 跟着我们一起学 Python 30天课程-第1天-简介
1. 本站资源转自互联网,源码资源分享仅供交流学习,下载后切勿用于商业用途,否则开发者追究责任与本站无关!
2. 本站使用「署名 4.0 国际」创作协议,可自由转载、引用,但需署名原版权作者且注明文章出处
3. 未登录无法下载,登录使用金币下载所有资源。
IT小站 » 跟着我们一起学 Python 30天课程-第23天-网页爬虫
常见问题FAQ
- 没有金币/金币不足 怎么办?
- 本站已开通每日签到送金币,每日签到赠送五枚金币,金币可累积。
- 所有资源普通会员都能下载吗?
- 本站所有资源普通会员都可以下载,需要消耗金币下载的白金会员资源,通过每日签到,即可获取免费金币,金币可累积使用。