python网页爬虫知识点
时间: 2023-12-29 21:26:39 浏览: 32
以下是关于Python网页爬虫的一些知识点:
1. 创建Spider类:在Scrapy项目的spiders目录下创建一个新的Python文件,定义一个类,继承自scrapy.Spider类,并给它一个名字。
```python
import scrapy
class MySpider(scrapy.Spider):
name = "my_spider"
```
2. 定义起始URL:在Spider类中定义一个start_urls列表,包含要爬取的起始URL。
```python
start_urls = [
'http://www.example.com/page1',
'http://www.example.com/page2',
]
```
3. 解析网页内容:在Spider类中定义一个parse方法,用于解析网页内容。可以使用XPath或CSS选择器来提取所需的数据。
```python
def parse(self, response):
# 使用XPath提取数据
title = response.xpath('//h1/text()').get()
content = response.xpath('//div[@class="content"]/text()').get()
# 使用CSS选择器提取数据
links = response.css('a::attr(href)').getall()
# 处理提取到的数据
# ...
# 返回提取到的数据
yield {
'title': title,
'content': content,
'links': links,
}
```
4. 爬取下一页:如果需要爬取多个页面,可以在parse方法中使用scrapy.Request发送新的请求。
```python
def parse(self, response):
# 解析当前页面的数据
# ...
# 发送请求爬取下一页
next_page_url = response.css('a.next-page::attr(href)').get()
if next_page_url:
yield scrapy.Request(url=next_page_url, callback=self.parse)
```
5. 存储数据:可以将爬取到的数据存储到数据库中,如MySQL或MongoDB,以便后续查询和管理。
```python
import pymongo
class MySpider(scrapy.Spider):
# ...
def parse(self, response):
# 解析网页内容
# ...
# 存储数据到MongoDB
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
collection.insert_one({
'title': title,
'content': content,
'links': links,
})
```