yay*_*ayu 2 python list-comprehension beautifulsoup filter
我正在抓取一个网页,该网页在其html标签中没有使用任何有用的类或ID,因此我不得不废弃所有链接并在链接中查找模式.以下是html示例的样子
<span>Category</span><link href='example.com/link-about-a'>A</a>
Run Code Online (Sandbox Code Playgroud)
在另一页上,我们可能有不同的类别
<span>Category</span><link href='example.com/link-about-b'>B</a>
Run Code Online (Sandbox Code Playgroud)
使用beautifulsoup4,我目前的解决方案看起来像这样
def category(soup):
for x in soup.find_all('a'):
if 'link-about-a' in x['href']:
return 'A'
if 'link-about-b' in x['href']:
return 'B'
Run Code Online (Sandbox Code Playgroud)
等等..但这很难看.
我想知道是否有办法让这个更简洁.
喜欢使用字典
categories = {'A': 'link-about-a', 'B': 'link-about-b'}
Run Code Online (Sandbox Code Playgroud)
并将其减少为单个表达式.
你需要的只是另一个循环:
for x in soup.find_all('a'):
for k, v in categories.iteritems():
if v in x['href']:
return k
Run Code Online (Sandbox Code Playgroud)
虽然如果你想要一个表达式:
category = next((
k for x in soup.find_all('a')
for k, v in categories.iteritems()
if v in x['href']
), None)
Run Code Online (Sandbox Code Playgroud)