gpt4 book ai didi

python - 根据用户在 Python 3 中选择的链接输入来计算网站中 p 标签 (

) 的数量

转载 作者:行者123 更新时间:2023-12-01 01:56:04 25 4
gpt4 key购买 nike

Write a program that asks the user for a URL. It should then retrieve the contents of the page at that URL and print how many <p> tags are on that page. Your program should just print an integer.

这是我的代码:

import urllib.request

link = input('Enter URL: ')
response = urllib.request.urlopen(link)
html = response.read()
counter = 0
for '<p>' in html:
counter += 1
print(counter)

但是,我收到了这个错误:

Traceback (most recent call last):

File "python", line 16

SyntaxError: can't assign to literal

执行此代码的更好方法是什么?我应该使用 find方法代替?

最佳答案

首先response.read()返回字节;因此你需要将其转换为字符串:

html = str(response.read())

那么,不需要for循环,你可以使用 count = html.counter('<p>')

希望有帮助

关于python - 根据用户在 Python 3 中选择的链接输入来计算网站中 p 标签 (<p>) 的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50182317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com