【发布时间】:2020-10-31 22:15:39
【问题描述】:
我一直在练习我的网页抓取技巧,遇到了一个问题,我通过抓取带有 id="secret-word" 的段落标签来过滤一组 10 个链接。我想出了如何为第一个链接执行此操作,所以我认为循环处理并一次获取它们会很好。
这是我从中获取链接的网站(链接位于底部):https://keithgalli.github.io/web-scraping/webpage.html
这是我想出的代码..但我无法弄清楚如何在不将其与 while 循环分开的情况下获取元素 0 (n=0)。也许你不能?
我拉出了所有链接的列表:
new_listc = links_with_text1[19:]
['challenge/file_1.html',
'challenge/file_2.html',
'challenge/file_3.html',
'challenge/file_4.html',
'challenge/file_5.html',
'challenge/file_6.html',
'challenge/file_7.html',
'challenge/file_8.html',
'challenge/file_9.html',
'challenge/file_10.html']
我使用请求连接到每个站点:
t = [requests.get(f"https://keithgalli.github.io/web-scraping/{url}", timeout=5) for url in new_listc]
我通过漂亮的汤循环了所有链接,并从每个链接中抓取了秘密单词以获取单词列表。我想知道是否有更简洁的方法可以做到这一点,以及为什么我必须将第一个挑战文件放在循环之外?!
n=0
tsoup = bs(t[n].content)
test_soup = tsoup.select("p#secret-word")
#print(n)
x = [t.text for t in test_soup]
print(x)
while n in range(0,9):
n += 1
#print(n)
tsoup = bs(t[n].content)
test_soup = tsoup.select("p#secret-word")
x = [t.text for t in test_soup]
print(x)
#print(tsoup.prettify())
if n > 9:
break
['Make']
['sure']
['to']
['smash']
['that']
['like']
['button']
['and']
['subscribe']
['!!!']
【问题讨论】:
-
这解决了它!:
code for n in range(len(oo)): count = count + oo[n] tsoup = bs(t[n].content) test_soup = tsoup.select("p#secret-word") for y in test_soup: print(y.text) code
标签: python-3.x web-scraping beautifulsoup