我在Python 2.7.13上使用BS4来解析我最终会放入CSV文件的网站上的论坛帖子。我的问题是,只有帖子中的第一篇帖子有关于帖子标题的数据,但我希望帖子的标题出现在我创建论坛帖子的CSV文件的每一行中。每行应该有帖子标题,帖子的作者,帖子的日期和时间,以及帖子的内容。当我搜索作者,日期/时间和内容时,我收到的结果与页面中的结果一样多,因此在这种情况下为19。因此CSV文件中应该有19行。但是,我只在CSV中收到一行输出,我认为这是因为BS4只能找到属性为“post-name”的“h4”标签的一个实例,而其他三个数据是多次找到的。
我可以编写代码,在页面中的所有帖子重复标题的第一个实例并将其放入CSV文档吗?我曾尝试使用if / else语法,但我还没有找到一种方法告诉BS4如果找不到后续帖子的标题,它应该只包含初始的汤。标题。
我真的很感谢你的帮助,因为我无法在任何地方找到解决方案。也许我在寻找错误的东西。这是我正在使用的代码:
from bs4 import BeautifulSoup
import csv
import urllib2
page = urllib2.urlopen("http://en.community.dell.com/support-forums/desktop/f/3513/t/20015349?pi21953=1")
soup = BeautifulSoup(page, "lxml")
one = soup.findAll("h4", attrs={"post-name"})
two = soup.findAll("a", attrs={"internal-link view-user-profile"})
three = soup.findAll("a", attrs={"internal-link view-post"})
four = soup.findAll("div", attrs={"post-content user-defined-markup"})
posttitle = []
poster = []
postdateandtime = []
postcontent = []
for post in one:
text = BeautifulSoup(str(post).strip()).get_text().encode("utf-8").replace("\n", " ")
posttitle.append(text.strip())
for post in two:
text2 = BeautifulSoup(str(post).strip()).get_text().encode("utf-8").replace("\n", " ")
poster.append(text2.strip())
for post in three:
text3 = BeautifulSoup(str(post).strip()).get_text().encode("utf-8").replace("\n", " ")
postdateandtime.append(text3.strip())
for post in four:
text4 = BeautifulSoup(str(post).strip()).get_text().encode("utf-8").replace("\n", " ")
postcontent.append(text4.strip())
csvfile = open('test.csv', 'wb')
writer = csv.writer(csvfile)
writer.writerow(["Post Title", "Poster", "Post Date and Time", "Post Content"])
for posttitle, poster, postdateandtime, postcontent in zip(posttitle, poster, postdateandtime, postcontent):
writer.writerow([posttitle, poster, postdateandtime, postcontent])
csvfile.close()
答案 0 :(得分:0)
您可以使用myArray[1000000] = true
参数zip_longest填充缺失值。只需给出posttitle的最后一个元素,以便最后一个标题用于所有缺失:
fillvalue