python-3.x - 网页抓取:无法抓取给定 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。标题也是一个列表。我如何获得每个标题和网址。
我正在尝试将部分刮成红色:
解决方案
首先, 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.
推荐阅读
- facebook-messenger - 在 Messenger 平台的 Facebook 按钮中添加额外的有效负载/ID
- node.js - 下划线作为前缀的属性的 eslint 问题
- python - 从命令行调用脚本时导入模块不起作用
- python - 插入双向链表的任意位置(不是开头或结尾)的问题
- python - Python/Curses:第一次按键没有任何反应
- java - Spring boot REST Api 的 Angular 客户端发布请求
- django - Django - 当主键已经存在时,使用 excel 文件更新数据库会导致错误
- algorithm - 利润取决于先前的工作时间 - 工作调度问题
- ruby - Ruby 哈希对齐
- perl - Perl 即发即弃 HTTP 请求