在Python中将多行字符串连接到数组中

2024-09-30 14:34:38 发布

您现在位置:Python中文网/ 问答频道 /正文

简而言之,我的代码应该从网站的HTML中的特定标记中提取文本(借助beautifulsoup4),然后将它们加载到一个数组中。你知道吗

我尝试过各种方法,但无法将多行字符串连接到单个数组中。你会怎么做?打印productBrands逐行返回文本。你知道吗

当前代码:

soup = BeautifulSoup(response.content)

productData = soup.find_all("div", {"class": "detail"})

for item in productData:
    productBrands = item.contents[1].text

Tags: 方法字符串代码标记文本网站responsehtml
2条回答

如果希望将每一行作为数组productBrands中的一个元素,那么可以创建一个空列表,并使用append将每一行添加到数组中。你知道吗

productBrands = []
for item in productData:
    productBrands.append(item)

据我所知,您需要在列表中收集get_text()的结果:

[product.get_text(strip=True) for product in soup.find_all("div", {"class": "detail"})]

请注意,在本例中,有一种较短的方法来定位元素—使用CSS选择器:

[product.get_text(strip=True) for product in soup.select("div.detail")]

相关问题 更多 >