【发布时间】:2016-05-15 17:23:42
【问题描述】:
我目前正在学习大数据课程,但不太了解。对于一项任务,我想了解关于阿姆斯特丹的 TripAdvisor 论坛上讨论了哪些主题。我想创建一个 CSV 文件,包括主题、作者和每个主题的回复量。一些问题:
- 如何列出所有主题?我检查了所有页面的网站源代码,主题总是在
'onclick="setPID(34603)'后面注明,并以</a>结尾。我试过'(re.findall(r'onclick="setPID(34603)">(.*?)</a>', post)' 但它不起作用。 - 回复不在 cmet 部分中给出,而是在页面上的单独行中给出。如何进行循环并将所有回复附加到新变量?
- 如何循环播放前 20 页?我的代码中的 URL 仅包含第一页,提供 20 个主题。
- 我是在循环之前还是之后创建 CSV 文件?
这是我的代码:
from urllib import request
import re
import csv
topiclist=[]
metalist=[]
req = request.Request('https://www.tripadvisor.com/ShowForum-g188590-i60-
Amsterdam_North_Holland_Province.html', headers={'User-Agent' :
"Mozilla/5.0"})
tekst=request.urlopen(req).read()
tekst=tekst.decode(encoding="utf-8",errors="ignore").replace("\n"," ")
.replace("\t"," ")
topicsection=re.findall(r'<b><a(.*?)</div>',tekst)
topic=[]
for post in topicsection:
topic.append(re.findall(r'onclick="setPID(34603)">(.*?)</a>', post)
author=[]
for post in topicsection:
author.append(re.findall(r'<a href="/members-forums/.*?">(.*?)</a>',
post))
replies=re.findall(r'<td class="reply rowentry.*?">(.*?)</td>',tekst)
【问题讨论】:
-
尽管我不想这么说,但如果您正在抓取网页,使用
xml.dom可能会获得最好的运气