【问题标题】:How can scrapy get the second <a href> inside of div class?scrapy 如何在 div 类中获取第二个 <a href> ?
【发布时间】:2020-02-27 12:12:56
【问题描述】:

我只是想从div class 中获取url。但是这个div 有两个&lt;a href&gt;。所以,这可以得到第一个,但应该得到第二个。我该怎么做?

这是网站的html代码:

 <div class="active"> 
          <a href="javascript:;" class=" add-favorite  j-lightbox-popup-button " data-target="howGoingCheckoutNotRedirect"> <i data-feather="heart"></i> </a> 
          <a href="/urun/yohegoalhareketli-kale-112432"> 

这是我的 Python 代码:

product_link = container.a["href"]

它在a["href"] 内部得到javascript:;

我所有的代码:

from bs4 import BeautifulSoup as soup
import pandas as pd
from tabulate import tabulate
import os
from joker import joker
import requests


product_joker_array = pd.DataFrame(columns = ['Shop Name','Product Name','Product Price','Product Image Url','Product Url']) 


for categories in range(0,len(joker.joker_category_names)):
    url = joker.joker_url  + joker.joker_category_names[categories]
    print(url)


    for pages in range(0,250):
        url = (joker.joker_url  + joker.joker_category_names[categories] + "#/page={}".format(pages))
        print(url)
        response = requests.get(url)
        data = response.text

        page_soup = soup(data, 'lxml')

        #time.sleep(10)
        containers = page_soup.findAll("div",{"class": "active"})
        #print(containers)
        len(containers)
        try:
            container = containers[0]
        except IndexError:
            print("Index Error")
            break

        #print(container)

        for container in containers:

            product_image = container.findAll("div", {"class": "image-link"})
            product_final_image = product_image[0].img["src"].strip()
            print("Product Image Url : " + product_final_image )

            product_desc = container.findAll("div", {"class": "image-link"})
            #print("asdasdas", product_desc)
            product_final_desc = product_desc[0].img["alt"].strip()
            print("product_final_desc : ",product_final_desc)

            #product_link = container.a["href"]
            product_link = container.xpath('.//a[2]/@href').extract_first()
            print("link : ",product_link)

            product_final_link = joker.joker_url + product_link
            print("final link : ",product_final_link)     



            product_price = container.findAll("span",{"class": "discount-price"})

            product_final_price = product_price[0].text.replace(" ", "")
            product_final_price = product_final_price.strip()
            print("product_final : ",product_final_price)
            #if "," not in product_final_price:
                                         #product_final_price = product_final_price + ",00"
                                         #print("product ,00",product_final_price)
            product_market_name = 'Joker'

            #print("Product Price:" + product_final_price )
            product_joker_array.loc[len(product_joker_array)] = [product_market_name,product_final_desc,product_final_price,product_final_image,product_final_link]

【问题讨论】:

    标签: python html scrapy css-selectors parsel


    【解决方案1】:

    如果你使用scrapy选择器方法来获取url,请使用以下语法:

    response.css('base::attr(href)').getall()
    

    【讨论】:

    • 出现这个错误:AttributeError: 'Response' object has no attribute 'css'
    • hmm.. 我建议从这个问题中删除 css 标签,因为我认为它与问题或答案无关.. 然后我看到你关联了一个基于 css 选择器的解决方案......如果这是一个可能的解决方案,你能纠正我的错误假设吗?
    • @AhmetYılmaz scrapy 的文档确实提到了使用 css 选择器的 .css() 扩展方法的存在。 (以及 xpath)。见selectors
    • 似乎依赖于parcel,所以这可能是您看到的问题。可能值得添加到这个答案。可能还想用parcelcss-selector 标记问​​题。
    • @BrettCaswell 好的。我添加了这两个标签。
    【解决方案2】:

    试试这个版本(从container 元素中获取href 以获得第二个a):

    container.xpath('.//a[2]/@href').extract_first()
    

    更新 看起来你有一个None 代表container。尝试这个: response.xpath('.//a[2]/@href').extract_first()

    【讨论】:

    • 我试过了。发生这个错误:TypeError: 'NoneType' object is not callable
    • 'Response' 对象没有属性 'xpath' 这就是问题所在。我认为container 应该是事实。因为我可以通过这种方式成功获得第一个a href
    • 你确定你在使用 Scrapy 吗?你是怎么得到container的?
    • 其实我也不确定。我只写 phyton 代码,但大部分代码都是从我的同事那里写的。它说import as beautiful soap。我可以在这里写它的所有代码。不多。
    • 我相信你根本没有使用 Scrapy :-(
    【解决方案3】:

    我用这些代码解决了这个问题:

    product_link = container.find("div", {"class": "active"})
                product_link = product_link.findAll("a")
                product_final_link = joker.joker_url + product_link[1]["href"]
    

    【讨论】:

      猜你喜欢
      • 2016-07-16
      • 1970-01-01
      • 2015-12-04
      • 2023-01-25
      • 1970-01-01
      • 2021-12-22
      • 2019-01-18
      • 2017-11-07
      • 1970-01-01
      相关资源
      最近更新 更多