【发布时间】:2018-06-23 13:21:44
【问题描述】:
我使用 BeautifulSoup 在 python 中编写了一个脚本,以获取位于左侧栏中的一些特定 URL,该 URL 位于网页标题为 VIDEOS BY YEAR 的章节中。问题是如果我在我的脚本中使用硬编码数字,我可以解析那些特定的 url,正如我已经在下面演示的那样。但是,我的目的是在我的脚本中不使用任何硬编码的数字来获取这些确切的 url。事实上,我正在寻找任何css selector 来做同样的事情。希望有人能伸出援助之手来完成这项工作。
这是我迄今为止尝试过的:
import requests
from bs4 import BeautifulSoup
URL = "https://www.wiseowl.co.uk/videos/"
response = requests.get(URL)
soup = BeautifulSoup(response.text,"html5lib")
for item in soup.select(".woMenuList .woMenuItem a")[-7:]:
print(item['href'])
它产生以下结果:
/videos/year/2011.htm
/videos/year/2012.htm
/videos/year/2013.htm
/videos/year/2014.htm
/videos/year/2015.htm
/videos/year/2016.htm
/videos/year/2017.htm
网址所在的HTML元素:
<ul class="woMenuList">
<li class="woMenuItem"><a href="/videos/year/2011.htm">2011 (19)</a></li>
<li class="woMenuItem"><a href="/videos/year/2012.htm">2012 (45)</a></li>
<li class="woMenuItem"><a href="/videos/year/2013.htm">2013 (29)</a></li>
<li class="woMenuItem"><a href="/videos/year/2014.htm">2014 (62)</a></li>
<li class="woMenuItem"><a href="/videos/year/2015.htm">2015 (25)</a></li>
<li class="woMenuItem"><a href="/videos/year/2016.htm">2016 (46)</a></li>
<li class="woMenuItem"><a href="/videos/year/2017.htm">2017 (24)</a></li>
</ul>
顺便说一句,所有类别和链接都在类似类型的类和标签中,这就是我卡住的原因。提前感谢您查看它。
【问题讨论】:
-
您能否改写您的问题或提供一些说明?我不太确定你在找什么
-
好吧,我希望通过使用 css 选择器从我的脚本中踢出这个硬编码的
[-7:]部分来获得相同的结果。 -
如果你删除
[-7:],你能提供输出的样子吗? -
没有切片应该“正常工作”...
-
是的。查看此链接以查看当我从脚本中删除该硬编码部分时得到的结果。 Link_to_the_results
标签: python python-3.x web-scraping beautifulsoup css-selectors