赞
踩
本次将分享8个Python爬虫的小案例,帮助大家更好地学习和了解Python爬虫的基础知识。以下是每个案例的简介和源代码:
需要Python全套学习资料的小伙伴可以扫描下方免费领取:
import re import requests from lxml import etree headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36" } # 定义小说首页地址 index_url = 'https://www.biquge11.cc/read/12972/' # 发送网络请求 response = requests.get(index_url, headers=headers) # 筛选链接和标题 info_list = re.findall('<dd><a href ="(.*?)">(.*?)</a></dd>', response.text) # 去除前面6个数据 info_list = info_list[6:] # 遍历列表,得到每章的部分链接和标题 for info in info_list: # 从元组中取出部分链接进行拼接,获取每章的页面链接 url = 'https://www.biquge11.cc' + info[0] # 获取数据 response = requests.get(url, headers=headers) html_data = etree.HTML(response.text) # xpath筛选出文本数据,并将数据列表转换成字符串 text_list = html_data.xpath('//div[@id="chaptercontent"]/text()') text = ''.join(text_list) # 添加标题行 book_text = '\n\n' + info[1] + '\n\n' # 去除广告文本 book_text += text.replace('请收藏本站:https://www.biquge11.cc。笔趣阁手机版:https://m.biquge11.cc ', '').replace(' ', '\n') print("正在下载:" + info[1]) print(book_text) # 保存到文件 with open('斗破苍穹.txt', 'a', encoding='utf-8') as file: file.write(book_text)
import time import requests import pandas as pd from datetime import datetime url = "https://kyfw.12306.cn/otn/userCommon/allProvince" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" } content_json = requests.get(url=url, headers=headers).json() print("等待3s") time.sleep(3) # 防止被检测(不要低于3) print(content_json) # 用于观察 # df = pd.DataFrame(content_json['data']) content_list = pd.json_normalize(content_json['data'], errors='ignore') if __name__ == '__main__': # 当前时间作为文件名后缀 curr_time = datetime.now() timestamp = datetime.strftime(curr_time, '%Y-%m-%d %H-%M-%S') # time = time.time() # 时间 # 将 DataFrame 保存为 excel 文件 content_list.to_excel(f"全国火车票代售点的省-{timestamp}.xlsx", index=False) print("保存完成!") # 查看 DataFrame 的行数和列数。 rows = content_list.shape print("请求得到的表格行数与列数:", rows)
# coding: utf-8 __author__ = 'Mac' __date__ = '19/10/31 15:05' import time from pynput.keyboard import Controller as key_cl from pynput.mouse import Button, Controller def keyboard_input(string): ''' :param string: 你想要发送的信息 :return: None ''' keyboard = key_cl() # 开始控制键盘 keyboard.type(string) # 键盘输入string def mouse_click(): # 点击发送消息 mouse = Controller() # 开始控制鼠标 mouse.press(Button.left) # 按住鼠标左键 mouse.release(Button.left) # 放开鼠标左键 def main(number, string): # 参数分别表示你要发多少条信息和发送的内容 time.sleep(5) # 此时暂停5s,方便你打开聊天窗,并把鼠标停放在发送按钮上 for i in range(number): # 用循环来控制你发送多少条消息 keyboard_input(string + str(i)) mouse_click() time.sleep(0.2) if __name__ == '__main__': main(500, "这里输入轰炸语句")
import requests import re # 请求URL url = '<http://www.zuihaodaxue.com/zuihaodaxuepaiming2019.html>' # 请求头部 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' } # 解析页面函数 def parse_html(html): pattern = re.compile('<tr class="alt">.*?<td>(.*?)</td>.*?<td><div align="left">.*?<a href="(.*?)" target="_blank">(.*?)</a></div></td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?</tr>', re.S) items = re.findall(pattern, html) for item in items: yield { '排名': item[0], '学校名称': item[2], '省市': item[3], '总分': item[4] } # 保存数据函数 def save_data(): f = open('university_top100.txt', 'w', encoding='utf-8') response = requests.get(url, headers=headers) for item in parse_html(response.text): f.write(str(item) + '\\\\n') f.close() if __name__ == '__main__': save_data()
import requests from lxml import etree import csv # 请求URL url = '<http://www.weather.com.cn/weather1d/101010100.shtml>' # 请求头部 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' } # 解析页面函数 def parse_html(html): selector = etree.HTML(html) city = selector.xpath('//*[@id="around"]/div/div[1]/div[1]/h1/text()')[0] temperature = selector.xpath('//*[@id="around"]/div/div[1]/div[1]/p/i/text()')[0] weather = selector.xpath('//*[@id="around"]/div/div[1]/div[1]/p/@title')[0] wind = selector.xpath('//*[@id="around"]/div/div[1]/div[1]/p/span/text()')[0] return city, temperature, weather, wind # 保存数据函数 def save_data(): f = open('beijing_weather.csv', 'w', newline='', encoding='utf-8-sig') writer = csv.writer(f) writer.writerow(['城市', '温度', '天气', '风力']) for i in range(10): response = requests.get(url, headers=headers) city, temperature, weather, wind = parse_html(response.text) writer.writerow([city, temperature, weather, wind]) f.close() if __name__ == '__main__': save_data()
import requests from lxml import etree import csv # 请求URL url = '<http://search.dangdang.com/?key=Python&act=input>' # 请求头部 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' } # 解析页面函数 def parse_html(html): selector = etree.HTML(html) book_list = selector.xpath('//*[@id="search_nature_rg"]/ul/li') for book in book_list: title = book.xpath('a/@title')[0] link = book.xpath('a/@href')[0] price = book.xpath('p[@class="price"]/span[@class="search_now_price"]/text()')[0] author = book.xpath('p[@class="search_book_author"]/span[1]/a/@title')[0] publish_date = book.xpath('p[@class="search_book_author"]/span[2]/text()')[0] publisher = book.xpath('p[@class="search_book_author"]/span[3]/a/@title')[0] yield { '书名': title, '链接': link, '价格': price, '作者': author, '出版日期': publish_date, '出版社': publisher } # 保存数据函数 def save_data(): f = open('dangdang_books.csv', 'w', newline='', encoding='utf-8-sig') writer = csv.writer(f) writer.writerow(['书名', '链接', '价格', '作者', '出版日期', '出版社']) response = requests.get(url, headers=headers) for item in parse_html(response.text): writer.writerow(item.values()) f.close() if __name__ == '__main__': save_data()
import requests from lxml import etree # 请求URL url = '<https://www.qiushibaike.com/text/>' # 请求头部 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' } # 解析页面函数 def parse_html(html): selector = etree.HTML(html) content_list = selector.xpath('//div[@class="content"]/span/text()') for content in content_list: yield content # 保存数据函数 def save_data(): f = open('qiushibaike_jokes.txt', 'w', encoding='utf-8') for i in range(3): url = '<https://www.qiushibaike.com/text/page/>' + str(i+1) + '/' response = requests.get(url, headers=headers) for content in parse_html(response.text): f.write(content + '\\\\n') f.close() if __name__ == '__main__': save_data()
import time from selenium import webdriver import requests # 请求URL url = '<https://weibo.com/>' # 请求头部 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' } # 解析页面函数 def parse_html(html): print(html) # 保存数据函数 def save_data(): f = open('weibo.txt', 'w', encoding='utf-8') browser = webdriver.Chrome() browser.get(url) time.sleep(10) browser.find_element_by_name('username').send_keys('username') browser.find_element_by_name('password').send_keys('password') browser.find_element_by_class_name('W_btn_a').click() time.sleep(10) response = requests.get(url, headers=headers, cookies=browser.get_cookies()) parse_html(response.text) browser.close() f.close() if __name__ == '__main__': save_data()
[最新全套【Python入门到进阶资料 & 实战源码 &安装工具】](安全链接,放心点击)
如果需要可以扫描下方二维码免费获取【保证100%免费】
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。