记录了在书上看到的一些方法,大体有用,不过代码本身有点老

[TOC]

使用request库请求网站

一、爬虫的基本原理

1.网页请求的过程

(1)Request(请求)

(2)Response(相应)

2.网页请求的方式

(1)GET:参数设置在URL中,是大多数网站的使用方式,只需一次发送和返回,响应速度快

(2)POST:通过request body传递参数,相比GET,可发送请求的信息大

二、使用GET方式抓取数据

复制任意一条首页首条新闻的标题,在源码页面按ctrl+F调出搜索框,将标题粘贴到搜索框,按回车。

标题在源码可以被搜索到,请求对象是www.***.cn,请求方式是GET。

确定好请求对象和方式后,输入代码。

1
2
3
4
import requests #导入reques包
url='https://www3.nhk.or.jp/news/' #这里选择的是NHK新闻网
strhtml=requests.get(url) #GET方式,并把获取到的数据保存在strhtml变量
print(strhtml.text)

微信截图_20240529161828

三、使用POST方式抓取数据

进入某翻译页面,按快捷键ctrl+shift+i进入开发者模式(F12也可以),在翻译页面输入文本并点击翻译。

在开发者模式中点击“网络”→“XHR”,在“负载”中找到翻译数据,单击“标头”,发现请求数据的方式为POST。

找到数据所在之处并且明确请求方式之后,接下来开始写代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import json
import requests

# POST请求的目标URL
def get_translate_date(word=None):
url = "https://dict.youdao.com/webtranslate"
Form_data = {
"type":"AUTO",
"i":"i love python",
"doctype":"json",
"xmlVersion":"1.8",
"keyfrom":"fanyi.web",
"ue":"UTF-8",
"action":"FY_BY_ENTER",
"typoResult":"true"
}
#使用requests.post请求表单数据
response = requests.post(url, data=Form_data)
#将字符串格式转换成json格式的数据,并提取打印
content = json.loads(response.text)
print(content['translateResult'][0][0]['tgt'])

get_translate_date('好的')

使用Beautiful Soup解析网页

1.用get抓取数据

2.提取数据

用选择器(select)定位数据:把鼠标光标移动到要定位的标题-右键-检查-复制selector

1
2
3
4
5
6
7
8
9
10
11
12
13
#调用bs4库
from bs4 import BeautifulSoup

import requests
url=('https://www3.nhk.or.jp/shutoken-news/nhk_shutoken.xml?_=1716982796021')
strhtml=requests.get(url)
print(strhtml.text)

#使用lxml解析网页文档
soup=BeautifulSoup(strhtml.text,'lxml')
data=soup.select('#main > article.module.module--news-main.index-main > '
'section > div.content--header > div > h1 > a > em')
print(data)

微信截图_20240529195222

3.处理网页编码问题

当爬取网页时,经常会遇到不同网页使用不同编码格式的情况。在处理网页编码问题时,我们可以使用 Requests 库的编码自动识别功能。

1
2
3
# 处理网页编码问题
response.encoding = response.apparent_encoding
print(response.text)

4.处理网络异常

在实际应用中,网络异常是常见的情况。为了保证爬虫的稳定性,应该对网络异常进行适当处理。我们可以使用 Try-Except 来捕获异常情况

1
2
3
4
5
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print("Error: %s" % e)

5.网页数据提取技巧

(1)提取文本信息

1
2
3
4
5
6
7
8
9
from bs4 import BeautifulSoup
import requests

url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
text = soup.get_text()
print(text)

(2)提取图片信息

将输出网页中所有图片的链接地址

1
2
3
4
5
6
7
8
9
from bs4 import BeautifulSoup
import requests

url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
images = soup.find_all('img')
for img in images:
print(img['src'])

(3)提取表格信息

按行或按列提取表格数据中的内容

1
2
3
4
5
6
7
8
9
10
11
12
from bs4 import BeautifulSoup
import requests

url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
table = soup.find('table')
rows = table.find_all('tr')
for row in rows:
cells = row.find_all('td')
for cell in cells:
print(cell.text)

(4)将数据保存在文件

将数据保存到名为 data.txt 的文本文件中

1
2
3
4
5
data = ['data1', 'data2', 'data3']

with open('data.txt', 'w') as file:
for item in data:
file.write(item + '\n')

(5)将数据保存在数据库

数据存储到名为 data.db 的 SQLite 数据库表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import sqlite3

conn = sqlite3.connect('data.db')
cursor = conn.cursor()

cursor.execute('''CREATE TABLE IF NOT EXISTS data_table (data text)''')

data = ['data1', 'data2', 'data3']

for item in data:
cursor.execute("INSERT INTO data_table (data) VALUES (?)", (item,))

conn.commit()
conn.close()

(6)将数据保存在表格中

1
2
3
4
5
6
import pandas as pd

data = {'A': [1, 2, 3], 'B': ['a', 'b', 'c']}
df = pd.DataFrame(data)

df.to_excel('data.xlsx', index=False)

6.数据清洗

处理提取数据中的异常情况

在爬虫过程中,数据有可能存在缺失、重复或异常格式等问题,需要进行各种异常情况处理,以下是一些常见的数据异常情况处理方法:

  • 数据去重:使用集合或字典对数据进行去重处理。
  • 缺失值处理:填充缺失值、删除缺失值、插值填充等方法。
  • 异常值处理:判断异常值的范围或利用异常检测算法进行处理。

数据清洗技巧

数据清洗是数据分析中至关重要的一环,有效的数据清洗可以提高数据质量和分析结果的准确性。以下是一些数据清洗的常用技巧:

  • 删除重复数据:通过唯一标识符或全部字段的对比删除重复数据。
  • 处理缺失值:填充缺失值、删除缺失值或使用聚合值填充方法。
  • 格式统一化:统一日期格式、字符串格式等,方便后续分析。
  • 异常值处理:判断异常值的来源及处理方式,避免对结果产生误导。

使用正则表达式辅助数据清洗

正则表达式在数据清洗中起到了关键的作用,它可以帮助我们快速匹配和提取符合规则的数据。以下是一些正则表达式在数据清洗中的应用场景:

  • 提取文本中的特定模式数据,如手机号码、邮箱地址等。
  • 对文本进行分割、替换和匹配,提取需要的信息。
  • 清洗特殊字符,去除无效信息或格式化数据。