在运行程序的发现报以下错误:
介绍下怎么解决这个简单问题:
显示每日IT榜单新闻,查了目前IT资讯信息网站:https://it.ithome.com/
查看网站,有日榜在右边:
F12查看HTML结构:
二话不说,直接上代码:
from selenium import webdriver
import time
import re
import datetime
browser = webdriver.Chrome()
url = 'https://it.ithome.com/'
browser.get(url)
time.sleep(3) # 这里必须要加3秒的延迟,因为有个刷新的动作需要等待下
data = browser.page_source
p_title = '<li><a title="(.*?)" target="_blank" href=".*?>.*?</a>'
p_href = '<li><a title=".*?" target="_blank" href="(.*?)">.*?</a>'
title = re.findall(p_title, data)
print(title)
href = re.findall(p_href, data)
print(href)
# 获取当前时间
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d"),"早上好,今日IT榜")
for i in range(10):
title_1 = title[i]
href_1 = href[i]
print(i + "、" + title_1)
print(href_1)
运行之后报错:
这是一个很简单的问题,i是int数字类型,但是在print的时候,因为用了加号,int类型不能直接和String类型相加,所以需要把int类型转换成String类型,就要用到str()这个方法
其实这里有两种办法可以解决问题,一种是把int转换成str,用str()方法,另外是用print的逗号
第一种、用str()方法,其他代码省略,只贴上报错代码:
for i in range(10):
title_1 = title[i]
href_1 = href[i]
print(str(i +1) + "、" + title_1)
print(href_1)
第二种,用print逗号隔开这个方法:
for i in range(10):
title_1 = title[i]
href_1 = href[i]
print(i+1, "、", title_1)
print(href_1)
改后就可以正常运行了
2022-10-12 早上好,今日IT榜
1 、 抖音集团上线新 LOGO
https://www.ithome.com/0/646/112.htm
2 、 外媒:扎克伯格正在犯一个典型的硅谷错误,Meta 成为了 10 年前的雅虎
https://www.ithome.com/0/646/042.htm
3 、 Meta 扎克伯格首次展示“元宇宙”完整头像:这次有腿了
https://www.ithome.com/0/646/045.htm
4 、 银保监会:已全面叫停新设网络小贷
https://www.ithome.com/0/646/095.htm
5 、 腾讯视频回应“双十一前或将接入 88VIP”:暂无计划,以官方公布为准
https://www.ithome.com/0/646/086.htm
6 、 腾讯地图 PC 端将于 11 月 11 日停止服务
https://www.ithome.com/0/646/125.htm
7 、 有些诡异,已故苹果创始人史蒂夫・乔布斯现身 AI 播客接受“采访”
https://www.ithome.com/0/646/108.htm
8 、 全球灯塔工厂名单再次刷新,宁德时代、海尔、美的等多家中国工厂上榜
https://www.ithome.com/0/646/023.htm
9 、 Facebook 母公司 Meta CEO 扎克伯格:苹果搞封闭,将成为元宇宙主要对手
https://www.ithome.com/0/646/049.htm
10 、 世界首富平时都怎么玩?揭秘马斯克的超级朋友圈
https://www.ithome.com/0/646/115.htm
如果有问题可以直接跟我留言。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/164029.html