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

标签 python html counter

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/

相关文章:

python - np.from函数 : Reference other arrays

python - 有没有办法在 App Engine 中实现长时间运行的事务?

html - 输入是否需要 "type"?

java - Android:提取两个 HTML 标签之间的文本

python - 如何在某个字符后停止读取输入?

html - CSS counter-increment - 从 100 开始计数器

python - 创建一个包含打印输出和绘图的文件

python - Python 中的多级分组 X 轴

javascript - .datepicker() 函数在第二次单击时起作用

perl - 需要 Perl 脚本来查找网络日志中找到的图像数量