python - 美丽的汤蟒 - 把名字放在一起/查找 - 找到所有
问题描述
我在喝漂亮的汤时遇到了麻烦。今天开始了解它,但无法找到解决我的问题的方法。
我每次只想得到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)
谢谢大家的答案。
解决方案
我假设您希望将其中的每一个都放入单独的列表中。
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])
推荐阅读
- html - 在哪里获取角度 http 元素的所有可绑定属性的列表?
- sql - 为什么关联数组中的最后一个元素(按表索引)不打印?
- flutter - ProviderNotFoundException(错误:找不到正确的提供者
在此 SchedulingPage Widget 上方使用 layoutBuilder - flutter - 如何在颤动的可扩展列表视图中显示数据
- r - 如何在 R 中的 Shiny 中调整我的侧边栏面板的大小?
- java - Java:转换 ByteBuffer 多维数组
- c++ - 无法找到错误,但编译器给出以下消息:
- c++11 - 为什么指向数组不同元素的两个指针之间的区别是这两个指针之间的元素数?
- arrays - 如何调用索引
- azure - 逻辑应用程序 - 从 Outlook 电子邮件触发器中获取所有 URL 并创建一个数组