首页 > 解决方案 > 美丽的汤蟒 - 把名字放在一起/查找 - 找到所有

问题描述

我在喝漂亮的汤时遇到了麻烦。今天开始了解它,但无法找到解决我的问题的方法。

我每次只想得到1个链接,h1和p中写的是什么。

article_name_list = soup.find(class_='turbolink_scroller')
#find all links in the div
article_name_list_items = article_name_list.find_all('article')

#loop to print all out
for article_name in article_name_list_items:
    names = article_name.find('h1')    
    color = article_name.find('p')
    print(names)
    print(color)

输出是:

<h1><a class="name-link" href="/shop/jackets/gw1diqgyr/km21a8hnc">Gonz Logo Coaches Jacket </a></h1>
<p><a class="name-link" href="/shop/jackets/gw1diqgyr/km21a8hnc">Red</a></p>

我想输出:href="blablabla" Gonz Logo Coatches Jacket Red

并每次将其放入一个变量中(如果可能的话),例如 link = href"blablabla" 和 name = "gonz logo ..." 或 3 个变量,其中颜色在另一个变量中。

编辑这里是页面的样子:

<div class="turbolink_scroller" id="container" style="opacity: 1;">
  <article>
    <div class="inner-article">
      <a style="height:150px;" href="/shop/jackets/h21snm5ld/jick90fel">
    <img width="150" height="150" src="//assets.supremenewyork.com/146917/vi/MCHFhUqvN0w.jpg" alt="Mchfhuqvn0w">
    <div class="sold_out_tag" style="">sold out</div>
  </a>
      <h1><a class="name-link" href="/shop/jackets/h21snm5ld/jick90fel">NY Tapestry Denim Chore Coat</a></h1>
      <p><a class="name-link" href="/shop/jackets/h21snm5ld/jick90fel">Maroon</a></p>
    </div>
  </article>
  <article></article>
  <article></article>
  <article></article>

</div>

编辑2:问题已解决(谢谢)

这是其他人的解决方案:

article_name_list = soup.find(class_='turbolink_scroller')
#find all links in the div
article_name_list_items = article_name_list.find_all('article')

#loop to print all out
for article_name in article_name_list_items:
    link = article_name.find('h1').find('a').get('href')
    names = article_name.find('h1').find('a').get_text()
    color = article_name.find('p').find('a').get_text()

    print(names)
    print(color)
    print(link)

谢谢大家的答案。

标签: pythonbeautifulsoup

解决方案


我假设您希望将其中的每一个都放入单独的列表中。

name_list = []
link_list = []
color_list = []
for article_name in article_name_list_items:
    names = article_name.find('h1').find('a', class_ = 'name-link').get_text()    
    links = article_name.find('p').find('a', class_ = 'name-link').get('href')
    colors = article_name.find('p').find('a', class_ = 'name-link').get_text()

    name_list.append(names)
    link_list.append(links)
    color_list.append(colors)

不完全确定article_name_list_items看起来像什么,但names会得到元素的文本<h1>links会得到href元素的<p>,并colors会得到<p>元素的文本。

您还可以选择在列表列表中包含所有元素,这将是(初始化新列表list_of_all并用第二行中的单个追加替换 3 个列表追加):

list_of_all = []
list_of_all.append([names, links, colors])

推荐阅读