以上问题如何更改
时间: 2024-02-17 20:04:38 浏览: 19
请参考以下代码,修改后应该可以正常发送请求了:
```python
# -*- coding: utf-8 -*-
import scrapy
from ..items import NpmItem
h = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.57'
}
class StartSpiderSpider(scrapy.Spider):
name = 'start_spider'
allowed_domains = ['www.plap.cn']
start_urls = ['https://www.plap.cn/index/selectIndexNewsByTypeId.html?page=1&id=110&title=']
def parse(self, response):
list_li = response.xpath('/html/body/div[3]/div[2]/ul/li')
for i in list_li:
items = NpmItem()
items['title'] = i.xpath('./a/@title').get()
items['time'] = i.xpath('./span/text()').get()
href = i.xpath('./a/@href').get()
url = response.urljoin(href)
yield scrapy.Request(url=url, headers=h, callback=self.detail, meta={'item': items})
# 继续访问下一页
next_page = response.xpath('//a[@class="next-page"]/@href')
if next_page:
next_url = response.urljoin(next_page.get())
yield scrapy.Request(url=next_url, headers=h, callback=self.parse)
def detail(self, response):
items = response.meta['item']
detail_url = response.xpath('/html/body/div[3]/div/div[2]/img/@src').get()
if detail_url:
detail_url = response.urljoin(detail_url)
items['detail'] = detail_url
yield items
```
修改内容:
1. allowed_domains 修改为 ['www.plap.cn']。
2. start_urls 放开注释。
3. 在 parse 函数中将 items 对象的创建移到 for 循环内,每个新闻的 title 和 time 都对应一个新的 items 对象。
4. 在 parse 函数中,加入对下一页的访问,避免只访问第一页。
5. 在 detail 函数中,使用 response.meta['item'] 获取传递的 items 对象,修正了之前的错误。
6. 在 detail 函数中,使用 response.urljoin() 方法将相对路径转换成绝对路径。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)