scrapy 用scrappy刮一些信息

mkshixfv  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(166)
import scrapy
from scrapy.http import Request
from bs4 import BeautifulSoup

class TestSpider(scrapy.Spider):
    name = 'test'
    start_urls = ['https://www.baroul-bucuresti.ro/index.php?urlpag=tablou-definitivi&p=1']

    def parse(self, response):
        base_url='https://www.baroul-bucuresti.ro'
        soup=BeautifulSoup(response.text, 'html.parser')
        tra = soup.find_all('div',class_='panel-title')
        productlinks=[]
        for links in tra:
            for link in links.find_all('a',href=True)[1:]:
                comp=base_url+link['href']
                yield Request(comp, callback=self.parse_book)

    d1=''
    def parse_book(self, response):
        title=response.xpath("//h1//text()").get()
        detail=response.xpath("//div[@class='av_bot_left left']//p")
        for i in range(len(detail)):

            if 'Decizia de intrare:' in detail[i].get():
                d1=response.xpath("//em[@class='ral_i']//text()").get()
                print(d1)

它们将提供以下输出:

Decizia de intrare:

但我想要的实际输出是这些,正如您在网站https://www.baroul-bucuresti.ro/avocat/15655/aanegroae-ana-maria的页面下看到的:

Decizia de intrare: 2469/1-06.12.16
zbq4xfa0

zbq4xfa01#

请尝试以下操作:
在if语句中,我没有使用根节点的xpath,而是使用了已经确定为包含所需文本的节点的xpath,然后我只是进行了一些字符串格式化。

def parse_book(self, response):
        title=response.xpath("//h1//text()").get()
        detail=response.xpath("//div[@class='av_bot_left left']//p")
        for i in range(len(detail)):

            if 'Decizia de intrare:' in detail[i].get():
                d1=detail[i].xpath('.//text()').getall()  
                d1 = " ".join([i.strip() for i in d1 if i.strip()])
                print(d1)

相关问题