作者onlyAPU (Nothing)
看板Python
标题[问题] 请教Beautifulsoup撷取文字的问题
时间Fri Jul 1 17:03:51 2022
各位好
我是程式小白,最近买了堂新手入门课程
尝试写了个PTT爬虫
并且只会print出有包含关键字的文章及连结
目前是可以执行,但是有以下图片的问题
想要只截取出网址的部分(图片红框部分),却找不到办法
https://imgur.com/a/rYe0880
以下是程式码
import requests
from bs4 import BeautifulSoup
import time
#这边以上是基本配置
# today = time.strftime('%m/%d').lstrip('0')
url = '
https://webptt.com/cn.aspx?n=bbs/Steam/index.html'
keyword = '特'
articles = []
for x in range(10):
resp = requests.get(url)
soup = BeautifulSoup(resp.text, 'html5lib')
paging = soup.find('div', 'btn-group
btn-group-paging').find_all('a')[1]['href']
rents = soup.find_all('div', 'r-ent')
for rent in rents:
title = rent.find('div', 'title').text.strip()
count = rent.find('div', 'nrec').text.strip()
date = rent.find('div', 'date').text.strip()
link = rent.find('a')
article = '%s %s %s %s' % (date, title, count, link)
try:
if keyword in title:
articles.append(article)
except:
if count == '爆':
articles.append(article)
url = '
https://webptt.com/cn.aspx?n=' + paging
if len(articles) != 0:
for article in articles:
print(article)
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 125.228.213.213 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1656666233.A.DF4.html
1F:→ blc: link['href'] 07/01 18:23
2F:推 tzouandy2818: 用一般字串处理的方式就好了吧 07/01 18:25
3F:推 lycantrope: link.get("href", "err:no_href") 07/01 18:25
我有尝试过改成link['href'].但是程式会出错
测试的时候有试过print(link['href']),这样是正常的
但是当我想要放到
article = '%s %s %s %s' % (date, title, count, link['href'])
执行就会错误
TypeError: 'NoneType' object is not subscriptable
※ 编辑: onlyAPU (125.228.213.213 台湾), 07/01/2022 18:36:03
4F:推 lycantrope: rent.find传回None就会Error 07/02 11:20
今天早上将程式码改成下面就可以了。谢谢
try:
link = rent.find('a')['href']
except:
link = None
#如果遇到删文href会是None type,所以要赋予一个值,才可以用APPEND
※ 编辑: onlyAPU (125.228.213.213 台湾), 07/02/2022 12:46:28
5F:推 lycantrope: 比较好的方式是用if处理; link_tag =rent.find("a") 07/02 13:23
6F:→ lycantrope: link= "" if link_tag is None else link_tag["href"] 07/02 13:24
7F:→ onlyAPU: 谢谢,来研究一下f'的用法,有时候直接输出变数会错误 07/02 15:46