Web Scraping 爬虫

key word : requests, urllib, beautifulsoup, scrapy

 

网页结构

HTML,CSS,JavaScript

HTML中,基本上所有实体内容都会有个tag来框住,被框住的内容被展现成不同内容和形式。

主体tag有head和body:

head中存放一些网页的源信息,比如title,这些信息不回被显示到网页中,大多时候是给搜索引擎的爬虫看

<head>
	<meta charset="UTF-8">
	<title>Scraping tutorial 1 | 莫烦Python</title>
	<link rel="icon" href="https://morvanzhou.github.io/static/img/description/tab_icon.png">
</head>

body中存放网页信息

<body>
    <h1>爬虫测试1</h1>
    <p>
        这是一个在 <a href="https://morvanzhou.github.io/">莫烦Python</a>
        <a href="https://morvanzhou.github.io/tutorials/scraping">爬虫教程</a> 中的简单测试.
    </p>
</body>

<h1> </h1> tag 存放标题

<p> </p> 存放的就是段落

<a> </a> 存放的就是连接

 

爬虫

from urllib.request import urlopen

# if has Chinese, apply decode()
html = urlopen(
    "https://morvanzhou.github.io/static/scraping/basic-structure.html"
).read().decode('utf-8')
print(html)

正则表达式匹配

import re
res = re.findall(r"<title>(.+?)</title>", html)
print("\nPage title is: ", res[0])
res = re.findall(r"<p>(.*?)</p>", html, flags=re.DOTALL)    # re.DOTALL if multi line
print("\nPage paragraph is: ", res[0])

BeautifulSoup

流程:

1. 选择 url

2. urlopen登陆网页

3. read() 读取网页星系, 有中文时需要decode('utf-8')

4. 将读取的信息放入 BeautifulSoup里

5. 使用BeautifulSoup选取tag信息(代替正则表达式)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值