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

时间:2016-07-19 02:18:22

标签: python arrays beautifulsoup

简而言之,我的代码应该从网站HTML中的特定标签中获取文本(在beautifulsoup4的帮助下),然后将它们加载到数组中。

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

当前代码:

soup = BeautifulSoup(response.content)

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

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

2 个答案:

答案 0 :(得分:1)

根据我的理解,您需要在列表中收集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")]

答案 1 :(得分:0)

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

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