在双引号内提取数据的有效方法

时间:2016-07-12 11:31:50

标签: python python-2.7 beautifulsoup

我需要从字符串中用双引号提取数据。

输入:

<a href="Networking-denial-of-service.aspx">Next Page →</a>

输出:

Networking-denial-of-service.aspx

目前,我正在使用以下方法执行此操作,并且运行正常。

atag = '<a href="Networking-denial-of-service.aspx">Next Page →</a>'
start = 0
end = 0

for i in range(len(atag)):
    if atag[i] == '"' and start==0:
        start = i
    elif atag[i] == '"' and end==0: 
        end = i

nxtlink = atag[start+1:end]

所以,我的问题是,还有其他有效的方法来完成这项任务。

三江源。

2 个答案:

答案 0 :(得分:2)

你标记了这个美丽的汤,所以我不明白为什么你想要一个正则表达式,如果你想要所有锚点的href那么你可以使用css select 'a[href]',它只能找到有href的锚标签属性:

h = '''<a href="Networking-denial-of-service.aspx">Next Page →</a>'''

soup = BeautifulSoup(h)

print(soup.select_one('a[href]')["href"])

或者找到:

 print(soup.find('a', href=True)["href"])

如果您有多个:

for  a in soup.select_one('a[href]'):
    print a["href"]

或者:

for  a in  soup.find_all("a", href=True):
     print a["href"]

您还可以指定您想要具有前导&#34;:

的href
 soup.select_one('a[href^="]') 

答案 1 :(得分:0)

我正在完全按照书面形式提出问题 - 如何在两个双引号之间获取数据。我同意HTMLParser可能更好的评论......

使用正则表达式可能会有所帮助,特别是如果您想要找到多个表达式。例如,这是一组可能的代码

import re
string_with_quotes = 'Some "text" "with inverted commas"\n "some text \n with a line break"'

Find_double_quotes = re.compile('"([^"]*)"', re.DOTALL|re.MULTILINE|re.IGNORECASE) # Ignore case not needed here, but can be useful.

list_of_quotes = Find_double_quotes.findall(string_with_quotes)

list_of_quotes

['text', 'with inverted commas', 'some text \n with a line break']

如果您有双引号的奇数,则忽略最后一个双引号。如果没有找到,则生成一个空列表。

各种参考资料

http://www.regular-expressions.info/非常适合学习正则表达式

Regex - Does not contain certain Characters告诉我如何不做角色

https://docs.python.org/2/library/re.html#re.MULTILINE告诉你re.MULTILINE和re.DOTALL(下面)是做什么的。

相关问题