【发布时间】:2019-06-02 21:16:18
【问题描述】:
在这方面有非常相似的场景;但我一直在和别人比较。
Getting from Clustered Nodes 等等。但不知何故;我不确定为什么我的for loop 没有迭代并从其他元素中获取文本,而只是从节点的第一个元素中获取。
from requests import get
from bs4 import BeautifulSoup
url = 'https://shopee.com.my/'
l = []
headers = {'User-Agent': 'Googlebot/2.1 (+http://www.google.com/bot.html)'}
response = get(url, headers=headers)
html_soup = BeautifulSoup(response.text, 'html.parser')
def findDiv():
try:
for container in html_soup.find_all('div', {'class': 'section-trending-search-list'}):
topic = container.select_one(
'div._1waRmo')
if topic:
print(1)
d = {
'Titles': topic.text.replace("\n", "")}
print(2)
l.append(d)
return d
except:
d = None
findDiv()
print(l)
【问题讨论】:
-
这行不应该是:topic = container.select_one('._1waRmo') - 换句话说,只是类名。 html_soup.find_all('div', {'class': 'section-trending-search-list'}) 行也只会找到根元素,你不需要 html_soup.find_all('div') 来枚举所有 div。或者如果你想枚举 div 类 _25qBG5 下的所有内容,然后找到它(称它为 toplevel,然后 options = toplevel.find('div') 然后 for option in options。
标签: python beautifulsoup