1

Python爬虫教程爬取HTML页面

 1 year ago
source link: https://www.2808proxy.com/practical-application-of-crawler/crawl-html-pages/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Python爬虫教程爬取HTML页面

无论您是想从网站获取信息、监控互联网变化,还是使用网站 API,网站爬虫都是访问所需数据的绝佳方式。 尽管它们包含许多部分,但爬虫基本上遵循一个简单的过程:它们下载原始数据,对其进行处理和提取,然后,如果需要,将数据保存在文件或数据库中。 您可以使用多种语言构建您的蜘蛛或爬虫,并且有多种方法可以实现这一点。

Python 是一种易于使用的脚本语言,具有广泛的库和附加组件,可用于创建程序,例如网站爬虫。 这些教程主要使用 Python 作为编程语言,其中很多使用了可以很容易地与 Python 爬虫代码连接的库,使开发过程更加顺利。

网页是结构化文档,因为在网站上使用 HTML 描述。 在保持其结构的同时从中获取数据有时可能是有利的。 网站并不总是以易于使用的格式提供数据,例如 CSV 或 JSON。

网络即将在这个时期出现。 使用计算机软件收集网页数据并将其排列成适当的格式,同时保持其结构称为网络爬行。

请求和 lxml

即使您使用的标签非常复杂,您也可以使用 lxml 扩展库 (http://lxml.de/) 轻松解析 XML 和 HTML 文档。 由于其速度和可读性,请求 (http://docs.python-requests.org/en/latest/#) 也将取代内置的 URLLIB2 模块。 这两个模块可以通过组合 PIP install lxml 和 PIP install requests 命令来安装。

让我们从 python 爬虫代码后面的导入开始:

from Import HTML Import Requests

接下来我们将使用 Requests。 HTML 模块,解析来自网页的数据,并将结果记录。

page = Requests.get (‘http://econpy.pythonanywhere.com/ex/001.html’= Html.fromstring (Page.text)

Tree 现在将整个 HTML 文件整齐地组织成树结构,可以使用 XPath 或 CSS 选择器进行访问。 在这种情况下,我们将选择第一个选项。

可以使用 XPath 在结构化文档(如 HTML 或 XML)中查找信息。 有关 XPath 的精彩介绍,请参阅 W3School。

有许多工具可用于获取元素的 XPath,包括 Chrome 的检查器和 Firefox 的 Firebug。 您可以突出显示代码,右键单击该元素,选择“检查元素”,如果您使用的是 Chrome,则选择“复制 XPath”。

简短的调查显示页面上的信息分为两个元素:标题为“Buyer-name”的 div 和类为“Item-price”的元素 span:

<div title=”buyer-name”class=”item-price”> $29.95</span>

知道了这一点,我们可以使用 lxml XPath 函数来构造适当的 XPath 查询,如下所示:

# This creates a list of buyers:buyers = Tree.xpath (‘//div[@title = ‘ buyer-name ‘]/text ()’)  # This will create a list of prices:prices = Tree.xpath (‘//span[@class = “Item-price”]/text () ‘)

看看我们得到了什么:

Print ‘Buyers:’, BuyersPrint ‘Prices:’, pricesbuyers: [‘Carson Busses’,’Earl E. Byrd.’,’Patty Cakes’,’Derri Anne Connecticut’,’Moe Dess’,’Leda Doggslife’,’Dan Druff’,’Al Fresco’,’Ido Hoe’,’Howie Kisses’,’Len Lease’,’Phil Meup’,’Ira Pent’,’Ben D. Rules’,’Ave sectomy’,’Gary Shattire’,’Bobbi soks’,’Sheila Takya’,’Rose Tattoo’,’Moe Tell’] Prices: [‘$29.95′,’$8.37′,’$15.26′,’$19.25′,’$19.25′,’$13.99′,’$10.09’]

通过lxml和request的使用,我们能够从一个网页中获得我们所需要的所有信息。 我们在脑海中列出它们,以便我们能够回忆起它们。 我们可以用它做各种事情,比如使用 python 爬虫代码来分析它或者保存一个文件并与大家分享。

我们可以考虑一些更酷的概念:使用多线程重新设计程序以加快速度,或者修改脚本以浏览示例数据集中的剩余页面。

python 爬虫教程,介绍如何使用 lxml 和 requests 模块爬取 HTML 页面

单线程、多线程、协程Python爬虫实战性能对比

Python爬虫实战介绍

为了比较网络爬虫中单线程、多线程、协程的性能,我想向大家展示如何使用标准的单线程、多线程、协程来爬取中农网产品的行情数据。

目标网址:中农网http://quote.product-htm-page-1.html

收集产品名称、最近报价、单位、报价编号、报价时间等数据,并保存到本地excel文件。

Python爬虫实战之爬行测试

网址更改政策在以下页面上:

  1. https://www.zhongnongwang.com/quote/product-htm-page-1.html
  2. https://www.zhongnongwang.com/quote/product-htm-page-2.html
  3. https://www.zhongnongwang.com/quote/product-htm-page-3.html

网页的结构在检查时很简单,使数据提取和解析变得简单。

思路:检索所有tr标签的内容,然后遍历所有tr标签,提取每个产品名称、最新报价、单位、报价编号、报价时间等信息。 每个产品报价信息都在类tb的table标签下的tbody下的tr标签中。

# -*- coding: utf-8 -*-  

@file : demo.py  

@author : Ye Tingyun  

@csdn: https://yetingyun.blog.csdn.net/  

import requests  

import logging  

from fake_useragent import useragent  

from lxml import etree  

# Basic configuration of log output  

logging.basicconfig(level=logging.info, format=’%(asctime)s – %(levelname)s: %(message)s’)  

# Randomly generate request headers  

ua = useragent(verify_ssl=false, path=’fake_useragent.json’)  

url = ‘https://www.zhongnongwang.com/quote/product-htm-page-1.html’  

# fake request header  

headers = {  

    “accept-encoding”: “gzip”, # Use gzip compression to transfer data for faster access  

    “user-agent”: ua.random  

# send request get response  

rep = requests.get(url, headersheaders=headers)  

print(rep.status_code) # 200  

# xpath locate and extract data  

html = etree.html(rep.text)  

items = html.xpath(‘/html/body/div[10]/table/tr[@align=”center”]’)  

logging.info(f’How many pieces of information on this page: {len(items)}’) # There are 20 pieces of information on a page  

# Traverse the extracted data  

for item in items:  

    name = ”.join(item.xpath(‘.//td[1]/a/text()’)) # item name  

    price = ”.join(item.xpath(‘.//td[3]/text()’)) # latest price  

    unit = ”.join(item.xpath(‘.//td[4]/text()’)) # unit  

    nums = ”.join(item.xpath(‘.//td[5]/text()’)) # number of quotes  

    time_ = ”.join(item.xpath(‘.//td[6]/text()’)) # Quote time  

    logging.info([name, price, unit, nums, time_]) 

使用Python爬虫实战爬取数据成功。

我给出了一个简单的单线程python爬虫教程。 可以看出,单线程爬虫一般是最快的,其次是单线程和多线程爬虫,都比较慢。 抓取也必须在上一页完成才能继续到下一页。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK