首页 > 解决方案 > 网页抓取:无法抓取给定 div、类的文本和 href 并跳过 span 标签

问题描述

试图获取热门新闻的文本和href,但无法抓取它。

网站:新闻网站

我的代码:

import requests
from bs4 import BeautifulSoup
import psycopg2
import time


def checkResponse(url):
    response = requests.get(url)
    if response.status_code == 200:
        return response.content
    else:
        return None


def getTitleURL():
    url = 'http://sandesh.com/'
    response = checkResponse(url)

    if response is not None:
        html = BeautifulSoup(response, 'html.parser')

    for values in html.find_all('div', class_='d-top-news-latest'):
        headline = values.find(class_='d-s-NSG-regular').text
        url = values.find(class_='d-s-NSG-regular').['href']
        print(headline + "->" + url)


if __name__ == '__main__':
    print('Getting the list of names....')
    names = getTitleURL()
    print('... done.\n')

输出:

Getting the list of names....
Corona live
મેડિકલ સ્ટાફ પર હુમલા અંગે અમિત શાહે ડોક્ટર્સ સાથે કરી ચર્ચા, સુરક્ષાની ખાતરી આપતા કરી અપીલ





Ahmedabad
ગુજરાતમાં કૂદકેને ભૂસકે વધ્યો કોરોના વાયરસનો કહેર, આજે નવા 94 કેસ નોંધાયા, જાણો કયા- કેટલા કેસ નોંધાયા





Corona live
જીવન અને મોત વચ્ચે સંઘર્ષ કરી રહ્યો છે દુનિયાનો સૌથી મોટો તાનાશાહ કિમ જોંગ! ટ્રમ્પે કહી આ વાત





Ahmedabad
અમદાવાદમાં નર્સિંગ સ્ટાફનો ગુસ્સો ફૂટ્યો, ‘અમારું કોઈ સાંભળતું નથી, અમારો કોરોના ટેસ્ટ જલદી કરાવો’





Business
ભારતીય ટેલિકોમ જગતમાં સૌથી મોટી ડીલ, ફેસબુક બની જિયોની સૌથી મોટી શેરહોલ્ડર


->http://sandesh.com/amit-shah-talk-with-ima-and-doctors-through-video-conference-on-attack/
... done.

我想跳过标签内的文本,而且我只能得到 1 个 href。标题也是一个列表。我如何获得每个标题和网址。

我正在尝试将部分刮成红色:

在此处输入图像描述

标签: python-3.xweb-scrapingbeautifulsoup

解决方案


首先, Atfor values in html.find_all('div', class_='d-top-news-latest')你不需要使用for,因为在 DOM 只有一个 class d-top-news=latest

其次,要获取标题,可以使用select('span')因为你的标题进入span标签。

第三,你知道标题是一个列表,所以你需要用它for来获取每个标题和 URL。

values = html.find('div', class_='d-top-news-latest')
for i in values.find_all('a', href = True):
    print(i.select('span'))
    print(i['href'])

输出

Getting the list of names....
[<span>
Corona live
</span>]
http://sandesh.com/maharashtra-home-minister-anil-deshmukh-issue-convicts-list-of- 
palghar-case/
[<span>
Corona live
</span>]
http://sandesh.com/two-doctors-turn-black-after-treatment-of-coronavirus-in-china/
[<span>
Corona live
</span>]
http://sandesh.com/bihar-asi-gobind-singh-suspended-for-holding-home-guard-jawans- 
after-stopping-officers-car-asi/
[<span>
Ahmedabad
</span>]
http://sandesh.com/jayanti-ravi-surprise-statement-sparks-outcry-big-decision-taken- 
despite-more-patients-in-gujarat/
[<span>
Corona live
</span>]
http://sandesh.com/amit-shah-talk-with-ima-and-doctors-through-video-conference-on- 
attack/
... done.

推荐阅读