import requests import random import parsel visited_urls = set() # 保存已经访问过的链接 page = 1 while True: # 循环爬取 url = f'https://travel.qunar.com/travelbook/list.htm?page={page}&order=hot_heat' html_data = requests.get(url).text selector = parsel.Selector(html_data) lis = selector.css('.list_item h2 a::attr(href)').getall() # 遍历当前页面中的所有链接 for li in lis: detail_url = 'https://travel.qunar.com' + li if detail_url in visited_urls: # 如果链接已经访问过,则跳过 continue visited_urls.add(detail_url) # 将链接加入集合中 detail_html = requests.get(detail_url).text time.sleep(random.randint(3, 5)) detail_selector = parsel.Selector(detail_html) title = detail_selector.css('.b_crumb_cont *:nth-child(3)::text').get() comment = detail_selector.css('.title.white::text').get() view_count = detail_selector.css('.view_count::text').get() date = detail_selector.css('#js_mainleft > div.b_foreword > ul > li.f_item.when > p > span.data::text').get() days = detail_selector.css('#js_mainleft > div.b_foreword > ul > li.f_item.howlong > p > span.data::text').get() money = detail_selector.css('#js_mainleft > div.b_foreword > ul > li.f_item.howmuch > p > span.data::text').get() character = detail_selector.css('#js_mainleft > div.b_foreword > ul > li.f_item.who > p > span.data::text').get() play_list = detail_selector.css('#js_mainleft > div.b_foreword > ul > li.f_item.how > p > span.data > span::text').getall() for play in play_list: print(play) print(title, comment, view_count, date, days, money, character, play_list, detail_url) time.sleep(random.randint(3, 5)) # 判断是否需要继续爬取 if len(lis) == 0 or page >= 20: break page += 1这段代码怎么将爬取出来的所有数据保存到csv文件
时间: 2024-03-27 09:36:22 浏览: 8
可以使用Python内置的csv库将数据保存到csv文件中。你需要先导入csv库,然后在代码中添加以下代码:
```python
import csv
# 将数据保存到csv文件中
with open('data.csv', mode='w', newline='') as csv_file:
fieldnames = ['title', 'comment', 'view_count', 'date', 'days', 'money', 'character', 'play_list', 'detail_url']
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
for data in all_data:
writer.writerow(data)
```
其中,`fieldnames`是csv文件中的每一列的标题,`all_data`是一个列表,包含了所有爬取到的数据。在循环中,我们将每一条数据写入csv文件中。最后通过`writerow`方法将数据写入csv文件。保存后,你可以在当前目录下找到`data.csv`文件。
相关问题
# 目标网站的URL url = "https://www.sucai999.com/pic/cate/263_460.html" # 发起请求并获取网页内容 response = requests.get(url) html_content = response.text # 创建BeautifulSoup对象 soup = BeautifulSoup(html_content, "html.parser") # 创建保存图片的文件夹 if not os.path.exists("images"): os.makedirs("images") # 计数器,用于限制爬取的图片数量 count = 5 # 查找所有的图片标签 image_tags = soup.find('a', class_='getword').find_all('img',class_='img1') print(image_tags) # 遍历图片标签,并下载图片 for img in image_tags: # 获取图片链接 img_url = img["data-src"] # 发起请求并获取图片内容 img_response = requests.get(img_url) # 保存图片到本地 with open(f"images/image{count}.jpg", "wb") as f: f.write(img_response.content) count += 1 # 爬取10张图片后停止 if count == 100: break print("爬取完成!")为什么这段代码只能爬取一张图片,请优化代码
这段代码只能爬取一张图片的原因是因为在查找图片标签时了`find`方法,该方法只返回第匹配到的元素。如果你想要取多张图片,可以`find_all`方法来获取所有匹配的图片标签。
下面是优化后的代码```python
import requests
from bs4 import BeautifulSoup
import os
# 目标网站的URL
url = "https://www.sucai999.com/pic/cate/263_460.html"
# 发起请求并获取网页内容
response = requests.get(url)
html_content = response.text
# 创建BeautifulSoup对象
soup = BeautifulSoup(html_content, "html.parser")
# 创建保存图片的文件夹
if not os.path.exists("images"):
os.makedirs("images")
# 计数器,用于限制爬取的图片数量
count = 0
# 查找所有的图片标签
image_tags = soup.find_all('a', class_='getword')[1:]
print(image_tags)
# 遍历图片标签,并下载图片
for img in image_tags:
# 获取图片链接
img_url = img.find('img', class_='img1')["data-src"]
# 发起请求并获取图片内容
img_response = requests.get(img_url)
# 保存图片到本地
with open(f"images/image{count}.jpg", "wb") as f:
f.write(img_response.content)
count += 1
# 爬取10张图片后停止
if count == 10:
break
print("爬取完成!")
```
在优化后的代码中,我使用了`find_all`方法来获取所有匹配的图片标签,并使用切片操作`[1:]`去掉了第一个标签,因为第一个标签是网站的Logo,并不是需要爬取的图片。然后在遍历图片标签时,通过`img.find('img', class_='img1')`来获取每个标签中的图片链接。
这样你就可以成功爬取多张图片了。如果你想要爬取更多的图片,可以将计数器`count`的值调大。记得在实际爬取过程中要遵守相关法律法规和目标网站的规定。
import requests from bs4 import BeautifulSoup # 定义主函数 if __name__ == '__main__': # 定义需要爬取的页面链接 urls = ['https://www.bernama.com/bm/am/news.php?id=2194049', 'https://www.bernama.com/bm/news.php?id=2194090'] # 循环遍历页面链接,并调用爬虫函数 for url in urls: spider(url) # 定义爬虫函数 def spider(url): response = requests.get(url) # 使用BeautifulSoup解析网页内容 soup = BeautifulSoup(response.text, 'html.parser') # 获取需要爬取的数据 data = soup.find_all('div', class_='col-12 col-sm-12 col-md-12 col-lg-8') # 将数据写入TXT文件中 with open('2.txt', 'a', encoding='utf-8') as f: for d in data: f.write(d.text + '\n') # 间隔一秒再进行下一次爬取 time.sleep(1)txt里面没有数据该如何改善
首先需要检查一下爬取的网页是否存在数据,可以在浏览器中手动访问这些链接,看看是否能够正常显示数据。如果网页中存在数据,可以尝试加入异常处理,捕获可能出现的异常。另外,可以加入一些调试信息,输出日志或者打印一些中间结果,以帮助定位问题。最后,也可以尝试使用其他的爬虫工具或者框架,比如Scrapy等,看看能否更好地爬取数据。