xpath爬虫示例代码
时间: 2023-03-03 21:39:21 浏览: 81
以下是一个使用XPath进行网页爬虫的示例代码:
```python
import requests
from lxml import etree
# 发送请求获取网页内容
url = 'http://example.com'
response = requests.get(url)
html = response.text
# 使用XPath解析网页内容
selector = etree.HTML(html)
title = selector.xpath('//title/text()')[0]
links = selector.xpath('//a/@href')
# 输出结果
print(title)
print(links)
```
这段代码首先使用 requests 库发送请求获取网页内容,然后使用 lxml 库的 etree 模块将网页内容解析成一个 Selector 对象。接着使用 XPath 表达式来提取网页中的标题和链接,最后将结果打印输出。
相关问题
爬虫 xpath 示例代码
以下是一个使用XPath进行爬取的示例代码:
```python
import requests
from lxml import etree
# 发送请求
response = requests.get('https://example.com')
# 解析HTML
html = etree.HTML(response.text)
# 使用XPath提取数据
title = html.xpath('//title/text()')[0]
links = html.xpath('//a/@href')
# 打印结果
print('网页标题:', title)
print('链接列表:')
for link in links:
print(link)
```
scrapy爬虫的示例代码
以下是一个使用Scrapy框架编写的简单爬虫示例代码:
```python
import scrapy
class MySpider(scrapy.Spider):
name = "myspider"
start_urls = [
'http://www.example.com/page1',
'http://www.example.com/page2',
]
def parse(self, response):
# 在这里解析页面,并提取需要的数据
# 使用XPath或CSS选择器进行定位和提取
data = response.xpath('//div[@class="example"]/text()').get()
# 构造item对象,用于存储提取的数据
item = {
'data': data,
}
yield item
# 如果需要翻页,可以通过yield一个Request对象来发送下一页的请求
next_page_url = response.xpath('//a[@class="next-page"]/@href').get()
if next_page_url:
yield scrapy.Request(response.urljoin(next_page_url), callback=self.parse)
```
这个示例中,爬虫类`MySpider`继承自`scrapy.Spider`,并定义了`name`和`start_urls`属性,并实现了`parse`方法。在`start_urls`中指定了起始页面的URL,`parse`方法用于解析页面并提取需要的数据。在`parse`方法中,可以使用XPath或CSS选择器来定位和提取数据。通过使用`yield`语句返回`item`对象,将提取的数据传递给爬虫框架进行处理。如果需要翻页,可以使用`yield`一个新的`scrapy.Request`对象来发送下一页的请求,然后通过指定`callback`参数来指定下一页请求的回调函数。