首页 文章

使用BeautifulSoup和Python从网页中提取两个文本字符串之间的文本

提问于
浏览
0

BeautifulSoup上有很多东西,但我找不到任何可以解决这个问题的东西...我想通过在代码中指定前后文本的位来提取两位html之间的文本 . 我可以使用Outwit Python模块执行此操作,但这次需要使用BeautifulSoup ...

我想要的页面位是下面的用户名:

<a class="generic_class" href="/people/username">

所以,我想通过告诉它寻找来指定beautifulsoup来刮取用户名

'a class =“generic_class”href =“/ people /'

之前刮去并停下来之后

'''

然后我希望它在csv的一个url循环中执行此操作(这已经有效),然后逐行将结果追加到新的csv(这个位可能不起作用):

for row in url_reader:
    url = row[0]
    page = br.open(url).read()
    soup = BeautifulSoup(br.response().read())
    user = soup.findAll('<a class="generic_class" href="/people/') # this is the line where the code that works should go! Obviously this bit does nothing as it doesn't extract what comes after, stopping at the closing quotation mark for the end of the href.
    page.append.user(output_file) # not sure if this is right?!

显然,在一个理想的世界里,我把它放在if / else中if(发现“找不到页面”)和其他(做上面的事情)来处理那些不起作用的url,但我会工作错误处理一次我真的可以使事情工作!那是我现在的首要任务......

任何帮助非常感谢 .

2 回答

  • 0

    你能不能只提取“href”属性值并解析那个?

    usernames = []
    
    for anchor in soup.findAll('a', {'class': 'generic_class'}):
        usernames.append(anchor['href'].split('/')[-1])
    
    with open('usernames.csv', 'ab') as f:
        writer = csv.writer(f)
        for username in usernames:
            writer.writerow([username])
    

    这只是一个简单的例子,我建议进行一些额外的验证等 .

  • 0

    您可以在 href 属性中传递一个函数:

    def start_with_people(href):
        return href and href.startswith('/people/')
    
    a_tags = soup.find_all('a', class_='generic_class', href=start_with_people)
    

    这将返回所有具有以 /people/ 开头的href的 <a> 标签 .

    一旦你有这些锚标签:

    • 你可以循环它

    • 获取 href

    • 拆分并获取用户名

相关问题