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/