import requests
from bs4 import BeautifulSoup
import re
import pandas as pd
# 设置请求头信息,模拟浏览器访问
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.3'}
# 定义一个函数来获取小红书的所有帖子
def get_all_posts(url):
# 发送GET请求
response = requests.get(url, headers=headers)
# 解析HTML内容
soup = BeautifulSoup(response.text, 'lxml')
# 提取帖子信息
posts = soup.find_all('div', class_='feed-item-root')
return posts
# 定义一个函数来提取帖子详细信息
def extract_post_info(post):
try:
# 提取帖子标题
title = post.find('a', class_='title-box').text.strip()
# 提取帖子链接
post_url = post.find('a', class_='title-box')['href']
# 提取作者昵称和昵称链接
author_info = post.find('div', class_='author-info').text.strip()
author_name = re.search('(.+)', author_info).group(1)
author_url = post.find('a', class_='author-name')['href']
# 提取作品类型
media_type = post.find('div', class_='media-type').text.strip()
# 提取阅读量
read_count = post.find('div', class_='read-count').text.strip()
# 提取点赞数
like_count = post.find('div', class_='like-count').text.strip()
# 提取评论数
comment_count = post.find('div', class_='comment-count').text.strip()
# 提取发布时间
publish_time = post.find('div', class_='publish-time').text.strip()
# 返回所有提取的信息
return {
'title': title,
'url': post_url,
'author_name': author_name,
'author_url': author_url,
'media_type': media_type,
'read_count': read_count,
'like_count': like_count,
'comment_count': comment_count,
'publish_time': publish_time
}
except Exception as e:
print(f'Error extracting post info: {e}')
return None
# 主函数
def main(max_pages):
# 初始化帖子列表和页码
posts = []
page = 1
# 循环遍历页面
while page <= max_pages:
print(f"Crawling page {page}")
# 构造页面URL
url = f'https://www.xiaohongshu.com/discovery/trending?page={page}'
# 获取页面所有帖子
all_posts = get_all_posts(url)
# 提取每个帖子的详细信息
for post in all_posts:
由于原始代码已经提供了一个很好的示例,以下是一个简化的代码实例,用于抓取小行星的直径数据:
import requests
from bs4 import BeautifulSoup
# 定义一个函数来获取小行星的直径数据
def get_asteroid_diameters(asterank_url):
# 发送HTTP请求
response = requests.get(asterank_url)
response.raise_for_status() # 检查请求是否成功
# 解析响应内容
soup = BeautifulSoup(response.text, 'html.parser')
# 找到包含直径信息的表格
table = soup.find('table', {'class': 'asterank'})
# 初始化直径列表
diameters = []
# 遍历表格中的所有行,跳过表头
for row in table.find_all('tr')[1:]:
# 提取直径数据
diameter = row.find_all('td')[4].text.strip()
diameters.append(diameter)
return diameters
# 使用函数获取小行星直径数据
asterank_url = 'https://www.asterank.com/neo.php'
diameters = get_asteroid_diameters(asterank_url)
# 打印直径数据
for diameter in diameters:
print(diameter)
这段代码简化了原始代码,去除了原始代码中的一些冗余部分,并且使用更为直接的方法来查找和提取小行星的直径数据。这个示例假设表格结构不会改变,如果结构发生变化,则需要更新解析代码以匹配新的结构。
import requests
from bs4 import BeautifulSoup
import datetime
def get_weather_data(city):
# 天气信息网站的URL模板
url = "http://www.weather.com.cn/weather/{}.shtml".format(city)
# 发送HTTP请求
response = requests.get(url)
# 解析网页
soup = BeautifulSoup(response.text, 'lxml')
# 提取天气信息
today_weather = soup.select('#7d .sky .temp')
today_temperature = today_weather[0].text
today_weather_icon = soup.select('#7d .sky img')[0]['src']
today_weather_info = soup.select('#7d .wea')[0].text.strip()
# 打印信息
print("城市:", city)
print("今日天气:", today_weather_icon, today_temperature, today_weather_info)
# 调用函数,传入城市名,例如 "北京"
get_weather_data("北京")
这段代码使用了requests库来发送HTTP请求,bs4库来解析网页,并使用select方法来定位HTML元素。然后,它提取了今日的天气信息,包括温度和天气状况,并打印出来。这个例子简单直观,适合作为爬虫入门学习的实例。
QCCSpider是一个智能化的数据采集框架,它提供了一种新的方式来处理网络爬虫的开发和数据采集过程。以下是一个使用QCCSpider的示例代码:
from qccspider.spider import Spider
from qccspider.selector import Selector
from qccspider.scheduler import Scheduler
from qccspider.pipeline import Pipeline
from qccspider.middlewares import Middlewares
# 初始化爬虫
spider = Spider()
# 定义爬虫的名字
spider.name = 'example_spider'
# 定义启动URL
spider.start_urls = ['http://example.com/']
# 定义解析函数
@spider.parse(Selector.type.XPATH, '//a[@href]', process_links=True)
def parse_example(self, response):
# 提取链接和文本
for link in response.css('a::attr(href)').extract():
yield {'url': link, 'text': response.css('a::text').extract_first()}
# 定义数据管道
pipeline = Pipeline()
@pipeline.process_item(item_type='*')
def print_item(item):
print(item)
# 运行爬虫
spider.run(pipeline=pipeline)
这段代码定义了一个简单的爬虫,它会从指定的URL开始,并提取页面中所有链接的URL和对应的文本。然后,使用Pipeline打印出每个抓取到的项目。这个例子展示了QCCSpider的基本用法,并且通过使用装饰器的方式定义了解析规则,使得代码更加简洁和易于理解。
import redis
class RedisClient:
"""
Redis客户端,用于管理Redis连接。
"""
def __init__(self, host='localhost', port=6379, db=0):
self.host = host
self.port = port
self.db = db
self._connection = None
def connect(self):
"""
建立到Redis服务器的连接。
"""
self._connection = redis.Redis(host=self.host, port=self.port, db=self.db)
def disconnect(self):
"""
关闭与Redis服务器的连接。
"""
if self._connection:
self._connection.close()
self._connection = None
def set(self, name, value, ex=None, px=None, nx=False, xx=False):
"""
设置键值对,使用与redis.Redis.set相同的参数。
"""
self._connect_if_needed()
return self._connection.set(name, value, ex, px, nx, xx)
def get(self, name):
"""
获取键的值,使用与redis.Redis.get相同的参数。
"""
self._connect_if_needed()
return self._connection.get(name)
def _connect_if_needed(self):
"""
如果尚未连接,则建立连接。
"""
if not self._connection:
self.connect()
# 使用示例
client = RedisClient()
client.set('key', 'value')
print(client.get('key'))
client.disconnect()
这段代码定义了一个名为RedisClient
的类,用于管理与Redis服务器的连接。它提供了连接和断开连接的方法,并且在需要时才建立连接。此外,它还提供了set
和get
方法,以便动态地存储和检索数据。这个类的实例可以用来进行基本的Redis操作,而无需手动管理连接的打开和关闭。
在Python中,使用XPath解析HTML内容通常涉及到lxml
库。以下是一个使用XPath解析网页内容的例子:
首先,安装lxml
库(如果尚未安装):
pip install lxml
然后,使用以下代码解析网页并提取所需的数据:
from lxml import etree
import requests
# 发送HTTP请求获取网页内容
url = 'http://example.com'
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 解析网页内容为XPath可以处理的对象
html = etree.HTML(response.text)
# 定义XPath表达式来选取需要的数据
# 例如://div[@class="content"]/ul/li/a
xpath_expression = 'YOUR_XPATH_EXPRESSION_HERE'
# 使用XPath表达式提取数据
results = html.xpath(xpath_expression)
# 处理提取的数据
for result in results:
# 提取每个li标签下的a标签的href属性和文本内容
href = result.get('href')
text = result.text
print(f'Href: {href}, Text: {text}')
else:
print("Failed to retrieve the webpage")
在这个例子中,你需要替换YOUR_XPATH_EXPRESSION_HERE
为你想要提取的数据的XPath表达式。这个表达式会告诉解析器如何在HTML文档中定位你感兴趣的元素。
请注意,XPath表达式的编写需要你对HTML结构有足够的了解。如果你想要提取的数据深藏在嵌套的标签之中,你可能需要编写一个复杂的XPath表达式来精确地定位它们。
import tkinter as tk
import requests
from bs4 import BeautifulSoup
def fetch_quotes(symbol):
url = f"https://finance.yahoo.com/quote/{symbol}"
response = requests.get(url)
if response.ok:
soup = BeautifulSoup(response.text, 'html.parser')
name = soup.find(id='quote-header-info').find('h1').text
price = soup.find(class_='My<span class="katex">\(b\)</span>').text
return f"{name} - {price}"
else:
return "Error fetching quote"
def update_quote(symbol):
quote = fetch_quotes(symbol.get())
quote_label.config(text=quote)
root = tk.Tk()
root.title("Yahoo Finance Stock Quote Fetcher")
root.geometry("400x200")
symbol_label = tk.Label(root, text="Enter stock symbol:")
symbol_label.pack()
symbol_entry = tk.Entry(root)
symbol_entry.pack()
fetch_button = tk.Button(root, text="Fetch Quote", command=lambda: update_quote(symbol_entry))
fetch_button.pack()
quote_label = tk.Label(root, text="")
quote_label.pack()
root.mainloop()
这段代码使用了tkinter
库来创建一个简单的用户界面,允许用户输入股票代码,并在点击按钮后获取该股票的名称和价格。这个例子教会了如何将爬虫逻辑集成到图形用户界面中,并展示了如何使用Python进行简单的GUI编程。
import requests
# 目标URL
url = 'http://example.com'
# 使用requests模块发送GET请求
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 请求成功,打印网页内容
print(response.text)
else:
# 请求失败,打印错误信息
print(f"请求失败,状态码:{response.status_code}")
这段代码演示了如何使用Python的requests模块来发送一个简单的GET请求并获取网页内容。首先,我们导入requests模块,然后指定我们想要访问的URL。接着,我们使用requests模块的get方法来发送一个GET请求到这个URL。最后,我们检查响应状态码,如果是200,则表示请求成功,我们打印出响应的文本内容;如果不是200,则表示请求失败,我们打印出状态码。
爬虫是一种自动提取网页数据的程序,用于数据采集。它可以帮助我们快速获取大量的信息,但同时也有可能触犯网站的反爬机制,导致被封号甚至法律问题。
- 安装requests和BeautifulSoup库
pip install requests
pip install beautifulsoup4
- 简单的爬虫示例
import requests
from bs4 import BeautifulSoup
url = 'http://example.com'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
for link in soup.find_all('a'):
print(link.get('href'))
这个例子中,我们使用requests库获取了网页内容,然后用BeautifulSoup进行解析,找出所有的a标签的href属性,也就是链接。
- 反爬虫策略
网站可能会通过各种方式阻止爬虫,如JavaScript动态渲染、Cookies验证、IP封禁等。
- 处理JavaScript渲染的页面
对于现今许多网站使用JavaScript动态渲染的情况,可以使用Selenium或者Pyppeteer等工具来处理。
- 使用代理和设置请求头
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:3128',
}
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.3',
}
response = requests.get('http://example.com', headers=headers, proxies=proxies)
- 应对反爬策略
如果网站设置了复杂的反爬机制,可以尝试以下策略:
- 使用代理轮换IP
- 限制爬取速度
- 使用用户代理(User-Agent)来模拟不同的浏览器访问
- 使用登录认证
- 爬虫与法律
遵守网站的robots.txt协议,不爬取不允许爬取的页面。未授权获取数据时,应确保你有权限获取数据,并遵守相关的法律法规。
以上是爬虫入门的基本概念和策略,实际应用中可能需要根据具体网站的反爬策略来调整策略和代码。
import requests
from bs4 import BeautifulSoup
import re
import pandas as pd
# 设置请求头,模拟浏览器访问
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.3'}
# 获取微博用户主页的网页内容
def get_page_content(url):
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
return None
except requests.RequestException:
return None
# 解析微博数据,提取微博正文
def parse_weibo_data(html):
soup = BeautifulSoup(html, 'lxml')
weibo_data = []
for container in soup.find_all('div', class_='c'):
weibo = {}
# 提取微博正文
text = container.find('span', class_='ctt')
if text:
weibo['text'] = text.text.strip()
else:
continue
# 提取转发数和评论数
for info in container.find_all('span', class_='cc'):
if '转发' in info.text:
weibo['retweet_count'] = re.search('\d+', info.text).group(0)
elif '评论' in info.text:
weibo['comment_count'] = re.search('\d+', info.text).group(0)
weibo_data.append(weibo)
return weibo_data
# 保存微博数据到CSV文件
def save_weibo_data_to_csv(weibo_data, file_name):
df = pd.DataFrame(weibo_data)
df.to_csv(file_name + '.csv', index=False, encoding='utf-8-sig')
# 主函数
def main(user_id, since_date, count):
url = f'https://weibo.com/p/100505{user_id}/home?is_search=0&visible=0&is_all=1&since_id=0&sort=time&page={count}'
html = get_page_content(url)
if html:
weibo_data = parse_weibo_data(html)
save_weibo_data_to_csv(weibo_data, f'weibo_data_{user_id}_{since_date}_{count}')
print(f'微博数据已保存到 weibo_data_{user_id}_{since_date}_{count}.csv')
else:
print('网页内容获取失败')
# 示例用户ID为1234567890,起始日期为2023-01-01,爬取第1页的数据
main(1234567890, '2023-01-01', 1)
在这个代码示例中,我们定义了一个main
函数,它接受用户ID、起始日期和页数作为参数,并将微博数据保存到CSV文件中。这个示例展示了如何使用Python进行网络爬取,提取特定的数据,并将其保存到文件中。需要注意