0

我以前可以在字符串中搜索关键字,但在使用列表时遇到了问题。我不断收到此错误。

TypeError: 'in <string>' requires string as left operand, not bool

我已经尝试了所有我能想到的解决方案,但这就是我现在所处的位置:

from BeautifulSoup import BeautifulSoup
import urllib2

keywords = ['diy','decorate', 'craft', 'home decor', 'food']

def get_tags(blog_soup):
    tags_html = blog_soup.find('div', attrs = {'style': 'margin-left: 60px; margin-bottom: 15px;'})
    tags = [tag.string for tag in tags_html.findAll('a')]
    string_tags = str(' '.join(tags))
    if any(keywords) in string_tags:
        print url

url = 'http://technorati.com/blogs/blog.mjtrim.com'
soup = BeautifulSoup(urllib2.urlopen(url).read())

get_tags(soup)
4

1 回答 1

2

为了使这项工作进行最小的更改,您可以更改any(keywords) in string_tags为以下内容:

any(keyword in string_tags for keyword in keywords)

或使用集合的替代方法:

keywords = set(['diy','decorate', 'craft', 'home decor', 'food'])

def get_tags(blog_soup):
    tags_html = blog_soup.find('div', attrs = {'style': 'margin-left: 60px; margin-bottom: 15px;'})
    tags = [tag.string for tag in tags_html.findAll('a')]
    if keywords.intersection(tags):
        print url
于 2013-09-04T18:47:47.000 回答