【问题标题】:How do I scrape hyperlink titles using BeautifulSoup?如何使用 BeautifulSoup 抓取超链接标题?
【发布时间】:2020-01-23 21:37:57
【问题描述】:

所以,我试图从中抓取的网站是:https//viewyourdeal-gabrielsimone.com'

产品名称和价格在每个 div 下 class= "info-wrapper" 我可以毫无问题地提取价格,但是当我尝试提取产品标题时,它无法将其转换为文本作为其 href 链接。每个产品名称都在 href 下的 div 类下。 所以我的问题是,我如何抓取产品名称?

import json
from bs4 import BeautifulSoup
import requests 
import csv
from datetime import datetime

url = 'https://viewyourdeal-gabrielsimone.com'

gmaInfo=[]
response = requests.get(url, timeout=5)
content = BeautifulSoup(response.content, "html.parser")
for info in content.findAll('div', attrs={"class" : "wrapper ease-animation"}):
    gridObject = {
            "title" : info.find('div', attrs={"class" : "title animation allgrey"}),
            "price" : info.find('span', attrs={"class":"red-price"}).text
            }
    print(gridObject)
    with open('index.csv', 'w') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow([gridObject])

【问题讨论】:

  • 但是类是:title animation allyellow
  • @GiovaniSalazar 我相信有不同的系列。我想要实现的是将 allyellow 或 allgrey 变成我可以放在 xml 上的文本。该类是 href 的一部分

标签: python beautifulsoup e-commerce


【解决方案1】:

我对我的 div 类过于具体,我将类更改为简单的标题,它工作正常。

【讨论】:

    【解决方案2】:

    使用以下代码,很少有项目返回 None。如果元素存在,只需提供 If 条件即可获取文本。

    from bs4 import BeautifulSoup
    import requests
    import csv
    from datetime import datetime
    
    url = 'https://viewyourdeal-gabrielsimone.com'
    
    gmaInfo=[]
    response = requests.get(url, timeout=5)
    content = BeautifulSoup(response.content, "html.parser")
    
    for info in content.findAll('div', attrs={"class" : "wrapper ease-animation"}):
       if info.find('div', attrs={"class": "title animation allgrey"}):
         gridObject = {
                "title" : info.find('div', attrs={"class" : "title animation allgrey"}).text.strip(),
                "price" : info.find('span', attrs={"class":"red-price"}).text
                }
         print(gridObject)
         with open('index.csv', 'w') as csv_file:
            writer = csv.writer(csv_file)
            writer.writerow([gridObject])
    

    【讨论】:

    • 感谢您的意见,我通过将其声明为标题而不是标题动画 allgrey 解决了这个问题。我太具体了
    猜你喜欢
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 2017-08-04
    • 2021-08-17
    相关资源
    最近更新 更多