'str'对象使用beautifulsoup没有属性'p' [英] 'str' object has no attribute 'p' using beautifulsoup

查看:139
本文介绍了'str'对象使用beautifulsoup没有属性'p'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在关注使用BeautifulSoup的教程,但是当我尝试阅读标题甚至段落时(使用soup.p),我收到一条错误消息,说:追踪(最近一次通话): 文件"*****/Tutorial1.py",第9行,在 pTag = soup.p AttributeError:'str'对象没有属性'p'"

I have been following a tutorial on using BeautifulSoup, however when I try to read the title or even paragraphs (using soup.p) I get an error saying, "Traceback (most recent call last): File "*****/Tutorial1.py", line 9, in pTag = soup.p AttributeError: 'str' object has no attribute 'p'"

我对Python还是很陌生,如果这些问题太简单了,不便打扰了,但是对您的帮助,我将不胜感激.代码如下:

I am still very new to Python, sorry to bother if these is too much of an easy issue but I will greatly appreciate any help. Code given below:

import urllib.request
from bs4 import BeautifulSoup


with urllib.request.urlopen('http://www.bbc.co.uk/sport/0/netball/33717953')    as response:
    page = response.read()
    soup = BeautifulSoup(page, "html5lib")
    soup = soup.prettify()
    pTag = soup.p

    print(pTag)

推荐答案

引用

prettify()方法将把Beautiful Soup解析树变成格式良好的 Unicode字符串,每个HTML/XML标记都位于其单独的行上.

The prettify() method will turn a Beautiful Soup parse tree into a nicely formatted Unicode string, with each HTML/XML tag on its own line.

您在此处将字符串设置为soup var:soup = soup.prettify().当然,字符串没有p属性,然后崩溃.

You set an string to soup var here: soup = soup.prettify(). Of course a string has not p property, then crashes.

要查找所有p:

...
page = response.read()
soup = BeautifulSoup(page, "html5lib")
for paragraph in soup.find_all('p'):
    do_something_with(paragraph)

这篇关于'str'对象使用beautifulsoup没有属性'p'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆