我不熟悉网络抓取。我无法从网页中获取字段(用户名)。
这是带有我感兴趣的字段的网页的HTML。
<div class="block-body">
<div class="block-row block-row--separated">
<div class="block-row block-row--separated">
<dl class="pairs pairs--columns pairs--fixedSmall">
<dl class="pairs pairs--columns pairs--fixedSmall">
<dl class="pairs pairs--columns pairs--fixedSmall">
<dl class="pairs pairs--columns pairs--fixedSmall">
<dl class="pairs pairs--columns pairs--fixedSmall">
<dl class="pairs pairs--columns pairs--fixedSmall">
<dl class="pairs pairs--columns pairs--fixedSmall">
<dt>YouTube Username</dt>
<dd>
GET_THIS_FIELD
</dd>
</dl>
<dl class="pairs pairs--columns pairs--fixedSmall">
以下是我面临的问题:
我无法提取该字段,因为有多个具有相同类的对象,text选项不起作用,并且我也不知道如何找到解决方案。
由于我要访问的所有页面中都不存在YOUTUBE USERNAME字段,因此我需要包含一个控件。
我尝试了一切,这只是最后一次尝试。
profile_content = profile.content
soup2 = BeautifulSoup(profile_content, features="lxml")
if soup2.find(text=re.compile('^YouTube Username$')):
user_channel = soup2.find("dl", {'class': 'pairs pairs--columns pairs--fixedSmall'}).find_next_siblings('dd')
else:
user_channel = "none"
谢谢您的帮助!
假设HTML代码正确,我可以提供此答案:
# data is the HTML code as string
soup = BeautifulSoup(data, 'html.parser')
the_field = soup.find('dt', string='YouTube Username').find_next('dd').text.strip()
print(the_field)
为了您自己的安全,如果找到了字符串,您可以添加测试,等等。希望这会有所帮助。