[英]python for loop is only returning first index item
正如标题所说的一切,我也查看了一些stackoverflow相同的问题,但我无法找到解决方案这是我的代码
r = requests.get("http://cpaleaks.com", headers={'User-agent': 'Mozilla/5.0 (X11; Ubuntu;
Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0'})
c = r.content
soup = BeautifulSoup(c,"html.parser")
all = soup.find_all("div",{"id":"content"})
all[0].find_all("h2")[0].text
for item in all:
print(item.find_all("h2")[0].text)
Output
6 Untapped Traffic Sources in 2019 That Convert With ANY Niche
预计 Output
必须是网站的所有标题
find_all("div",{"id":"content"})
将为您提供一个<div>
及其内部元素树的结果集,因此您只迭代一次并仅打印一次文本第一个<h2>
print(item.find_all("h2")[0].text)
在find_all('h2')
时迭代结果集中的第一个元素:
for item in all[0].find_all("h2")
print(item.text)
或者在我看来更具体和更清洁的解决方案,迭代所有<h2>
元素(div)中具有 id 内容的选择:
for item in soup.select('#content h2'):
print(item.text.strip())
import requests
from bs4 import BeautifulSoup
import pandas as pd
r = requests.get("http://cpaleaks.com", headers={'User-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0'})
c = r.content
soup = BeautifulSoup(c,"html.parser")
for item in soup.select('#content h2'):
print(item.text.strip())
6 Untapped Traffic Sources in 2019 That Convert With ANY Niche
3 SECRET Steps to Make Money on Instagram WITHOUT Followers – Fast & Efficient
Facebook Marketing in 2019 – SMART Strategies + Case Study!
Rank Local Businesses on the FIRST page of Google – Profit from NOOBS like a PRO!
Reddit is STILL Endless Source Of FREE Marketing Traffic – IF DONE RIGHT!
How To EXPLODE Your Earnings With HOT Targeted Pins on Pinterest
The Key In the LIST! Grow Your Subscriber Count Super FAST – Build Your Money Making MACHINE!
How to Monetize Virtual Businesses on Groupon and Make Up To $100K THIS YEAR
Laser Targeted Quora Strategy to Profit With Clickbank Products – QUORA DONE RIGHT!
我不确定 beautifulsoup 是如何工作的,但也许可以尝试使用此代码而不是最后的 for。
for h2 in all[0].find_all("h2")
print(h2.text)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.