爬虫程序的实现

tianticheng / 2024-03-06 / 原文

0.学习爬虫的入门

看的第一个视频就是手把手的讲解怎么写爬虫程序,对小白非常的友好,强烈推荐。(写新的程序就是照葫芦画瓢)

【Python+爬虫】爆肝两个月!拜托三连了!这绝对是全B站最用心(没有之一)的Python+爬虫公开课程,从入门到(不)入狱 !_哔哩哔哩_bilibili

1.插件

所有的爬虫程序都要用到requests插件,有了这个才能实现对网页的访问(好像是),而在获取了网站的数据后还要进行数据的处理,这是一个非常繁杂的过程,需要用到bs4包里的"BeautifulSoup" 插件,就可以化繁为简。

 import requests
 from bs4 import BeautifulSoup

2.前期配置

绝大部分网站都不能允许爬虫程序打直球地访问,在写代码之前要先伪装一下自己的代码,让网站以为是一个正经八百的浏览器在浏览他。

随便找一个网页,右键点击检查,在网络界面中,选择任意一串,之后找到”User-Agent“这一项,把他复制后按照如下形式写出

headers = {
    "User-Agent": "xxxxxxxx"(此处为你获取的数据)
}

至此,前期所有的准备都结束了,可以正式进行代码的实现了

3.代码主体

用"url"来代表进行访问的网址。

url  = 'xxx'

接下来使用两个插件开始访问和获取网站的数据

response = requests.get(url, headers=headers)
content = response.content.decode('utf8')
soup = BeautifulSoup(content, "lxml")

之后通过筛选来的得出自己想要的内容

4.代码实例(包含csv)

以https://www.ign.com.cn/top-100-180327/20749/top100/li-shi-zui-jia-top-100you-xi-pan-dian为例

# 爬ign历史100佳游戏排名 原网址https://www.ign.com.cn/top-100-180327/20749/top100/li-shi-zui-jia-top-100you-xi-pan-dian
# 排名顺序从100到1

import requests
import csv
from bs4 import BeautifulSoup


url = 'https://www.ign.com.cn/top-100-180327/20749/top100/li-shi-zui-jia-top-100you-xi-pan-dian'

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"
}

response = requests.get(url, headers=headers)
content = response.content.decode('utf8')
soup = BeautifulSoup(content, "lxml")
ranks = soup.findAll(id="id_title")
output = ranks
print(type(output))
with open('游戏排名.csv', 'a+', encoding='utf-8',newline='') as f:
    w = csv.writer(f)
    w.writerows(output)

with open('游戏排名.csv', 'r', encoding='utf-8',newline='') as f:
    csv_reader = csv.reader(f)
    for row in csv_reader:
        print(row)



完成了数据的获取