import requests import re url='https://bbs.hcbbs.com' html=requests.get(url) html.encoding='GBK' #读取网页源码 reg=r'<a href="(.*?)" title=".*?" target="_blank">(.*?)</a>' #写出所需要的正则表达式 titre=re.compile(reg,re.I) #创建正则表达式对象 urls=titre.findall(html.text) print(urls) f=open('D://aaaaa.csv','a') for titu in urls: f.write(titu[0]+','+titu[1]+'\n') #csv文件以逗号分隔 f.close() 写出该段代码的设计步骤
时间: 2024-03-31 07:37:28 浏览: 117
这段代码的设计步骤如下:
导入 requests 和 re 模块。
定义需要爬取的网页 URL。
使用 requests 模块获取网页源码,并将其编码方式设置为 GBK。
编写正则表达式,用于匹配网页中的目标信息。
使用 re 模块创建正则表达式对象。
使用 findall 方法,从 html.text 中匹配出所有符合正则表达式的信息,并将其保存到 urls 列表中。
打开一个 CSV 文件,并以追加模式写入数据。
遍历 urls 列表中的元素,将其第一项和第二项以逗号分隔的形式写入 CSV 文件中。
关闭 CSV 文件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![py](https://img-home.csdnimg.cn/images/20250102104920.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)