使用BeautifulSoup的find和find_all函数获取标签的问题

在爬虫时遇到下面的导航树:

——div.center
    ——div.ft_ggbox_1 balck_ggbox_1
        ——div.black_jubao_right black_jubao_right_xxbh black_jubaot_xxbh
            ——form#listform
                ——p
                ——a
                    ——div.ft_publick_pzxx
                        ——div.ft_publick_pzxxright ft_publick_myjb
                ——p
                ——a

如果使用find函数,只能找到第一个a标签,下面的a都无法找到,但是如果用find_all函数,又会把a的child全提取,但实际上我只想提取所有a的href而已,这个问题我该怎么解决呢?

阅读 15.7k
3 个回答

提问问题的姿势不对,这样子别人很难为你解答,应该给出网页的完整结构。

from bs4 import BeautifulSoup

url = 'https://segmentfault.com/'
html = requests.get(url).content

soup = BeautifulSoup(html, 'lxml')
for hrefs in soup.find_all('a'):
    print(hrefs.get('href'))
    

clipboard.png
这样子不就可以了

导航树是自动生成的吗?

首先通过find_all找到所有a标签, 然后通过列表表达式将所有a包含的href保存到列表中

soup = BeautifulSoup(html_string)
atag = soup.find_all('a')
hrefs = [item.get('href') for item in atags if item.get('href')]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题