关于 https://www.hltv.org/matches页面,比赛除以日期,但类(class)相同。我的意思是,
这是今天的比赛课
<div class="match-day"><div class="standard-headline">2018-05-01</div>
这是明天的比赛课。
<div class="match-day"><div class="standard-headline">2018-05-02</div>
我想做的是,我想获取“标准标题”类下的链接,但仅限今天的比赛。比如,获得唯一的第一个。
这是我的代码。
import urllib.request
from bs4 import BeautifulSoup
headers = {} # Headers gives information about you like your operation system, your browser etc.
headers['User-Agent'] = 'Mozilla/5.0' # I defined a user agent because HLTV perceive my connection as bot.
hltv = urllib.request.Request('https://www.hltv.org/matches', headers=headers) # Basically connecting to website
session = urllib.request.urlopen(hltv)
sauce = session.read() # Getting the source of website
soup = BeautifulSoup(sauce, 'lxml')
matchlinks = []
# Getting the match pages' links.
for links in soup.find_all('div', class_='upcoming-matches'): # Looking for "upcoming-matches" class in source.
for links in soup.find_all('a'): # Finding "a" tag under "upcoming-matches" class.
clearlink = links.get('href') # Getting the value of variable.
if clearlink.startswith('/matches/'): # Checking for if our link starts with "/matches/"
matchlinks.append('https://hltv.org' + clearlink) # Adding into list.
最佳答案
实际上,该网站首先显示今天的比赛(在顶部),然后是接下来几天的比赛。所以,如果你想获得今天的比赛,你可以简单地使用 find()
,返回找到的第一个匹配项。
使用它会给你你想要的:
today = soup.find('div', class_='match-day')
但是,如果您想明确指定日期,您可以使用 text='2018-05-02'
找到包含今天日期的标签。作为 find()
的参数方法。但是,请注意,在页面源代码中,标签是 <span class="standard-headline">2018-05-02</span>
而不是 <div>
标签。得到这个标签后,使用 .parent
得到<div class="match-day">
标签。
today = soup.find('span', text='2018-05-02').parent
同样,如果你想让解决方案更通用,你可以使用 datetime.date.today()
而不是硬编码的日期。
today = soup.find('span', text=datetime.date.today()).parent
您必须导入 datetime
模块。
关于python - 如何在两个相同的类(class)之间只获得一流的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50120344/