如何获得第二个子元素?

时间:2014-02-18 14:49:41

标签: python python-3.x beautifulsoup

请帮助修复脚本。

import urllib.request
import urllib.parse
import re

import requests
import bs4

beginIndex = 1000
endIndex = 1010
prefix = "http://www.inpic.ru"

for i in range(beginIndex, endIndex):
    req = requests.get(prefix + '/image/' + str(i))
    if req.status_code == requests.codes.ok:
        print(i, '\t', req.status_code, '\t', req, end='\n')
        soup = bs4.BeautifulSoup(req.content)
        #print(soup.prettify())
        name = soup.find("td", {"class": "post_title"}).contents[1].contents
        author = soup.find("td", {"class": "post_title"}).contents[2].contents[1].contents
        #name = replace(name, '/', '_')
        print(name, '\t', author)    

错误消息:

Traceback (most recent call last):   File
"C:\VINT\OPENSERVER\OpenServer\domains\localhost\python\parse_html\1\q.py",
line 19, in <module>
    author = soup.find("td", {"class": "post_title"}).contents[2].contents[1].contents   File
"C:\Python33\lib\site-packages\bs4\element.py", line 675, in
__getattr__
    self.__class__.__name__, attr)) AttributeError: 'NavigableString' object has no attribute 'contents'

问题是无法列出具有类“date_author”的元素的内容。我只需要使用命令“contents”(NOT nextSibling等)

1 个答案:

答案 0 :(得分:1)

使用

soup.find("td", {"class": "post_title"}).contents[1].string

soup.find("td", {"class": "post_title"}).contents[1]NavigableString