python3 使用BeautifulSoup爬取网页内容保存到csv

本文介绍了如何使用Python3的BeautifulSoup库爬取房天下的租房信息,包括户型、租金、面积等字段。由于网站没有反爬机制,故无需代理IP。文中提到部分信息需在详情页获取,为此编写了爬取详情页的函数,并最终将数据保存到CSV文件中。
摘要由CSDN通过智能技术生成

以爬取房天下的租房信息为例:
需要爬取的字段有,户型,租金,面积,朝向,楼层,装修情况,标签,小区名称,地区
因为这个网站没有反爬虫所以不需要用到代理IP

#导入模块
from bs4 import  BeautifulSoup
import requests
def crawlFang(url,data,href): #定义一个爬取字段的函数
    res = requests.get(url)
    html=res.text            #获取网页内容
    #获取BeautifulSoup对象
    soup=BeautifulSoup(html,'html.parser')
                                              #寻找需要爬取内容的标签
    div=soup.find('div',class_="houseList")
    divs=div.find_all('dl',class_="list hiddenMap rel")
    divs.pop(10)                                      #第十一个标签是广告需要删掉
    for each in divs:
        #因为户型,朝向,是在一个字段中的,先把整个文本提取出来
        text=each.find('dd',class_="info rel").find('p',class_="font15 mt12 bold").get_text().strip().split('|')
        #户型
        pattern=text[1]        #在文本中在
要将爬取的网页内容保存CSV文件中,可以使用Python中的csv模块。具体步骤如下: 1. 导入相关模块: ```python import requests import csv from bs4 import BeautifulSoup ``` 2. 发送HTTP请求,获取网页内容: ```python url = 'http://www.example.com' response = requests.get(url) html_content = response.content ``` 3. 解析HTML内容,获取需要的信息: ```python soup = BeautifulSoup(html_content, 'html.parser') title = soup.title.string text = soup.get_text() ``` 4. 将获取的信息写入CSV文件: ```python with open('example.csv', 'w', encoding='utf-8', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(['Title', 'Text']) writer.writerow([title, text]) ``` 注意事项: - `csv.writer()`中`newline=''`参数的作用是防止写入CSV文件时出现空行; - CSV文件的编码一般为`utf-8`,中文字符需要特别注意编码问题。 完整代码示例: ```python import requests import csv from bs4 import BeautifulSoup url = 'http://www.example.com' response = requests.get(url) html_content = response.content soup = BeautifulSoup(html_content, 'html.parser') title = soup.title.string text = soup.get_text() with open('example.csv', 'w', encoding='utf-8', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(['Title', 'Text']) writer.writerow([title, text]) ``` 执行完毕后,当前目录下会生成一个名为`example.csv`的文件,文件内容爬取的网页标题和文本。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值