【发布时间】:2020-08-08 16:31:36
【问题描述】:
我正在从圣诞树农场网站上抓取链接。首先,我使用本教程method 获取所有链接。然后,我注意到我想要的链接没有使用正确的超文本传输协议,所以我创建了一个变量来连接。现在我正在尝试创建一个if 语句来获取每个链接并查找后跟“xmastrees.php”的任何两个字符。如果这是真的,那么我的连接变量将放在它的前面。如果链接不包含特定文本,则将其删除。例如 NYxmastrees.php 将是 http://www.pickyourownchristmastree.org/NYxmastrees.php 并且 ../disclaimer.htm 将被删除。我尝试了多种方法,但似乎找不到合适的方法。
这是我目前拥有并不断遇到语法错误的内容:del。我注释掉了那行并得到另一个错误,说我的字符串对象没有属性're'。这让我很困惑,因为我虽然可以将正则表达式与字符串一起使用??
source = requests.get('http://www.pickyourownchristmastree.org/').text
soup = BeautifulSoup(source, 'lxml')
concatenate = 'http://www.pickyourownchristmastree.org/'
find_state_group = soup.find('div', class_ = 'alert')
for link in find_state_group.find_all('a', href=True):
if link['href'].re.search('^.\B.\$xmastrees'):
states = concatenate + link
else del link['href']
print(link['href']
else del link['href'] 出错:
else del link['href']
^
SyntaxError: invalid syntax
没有else del link['href'] 的错误:
if link['href'].re.search('^.\B.\$xmastrees'):
AttributeError: 'str' object has no attribute 're'
【问题讨论】:
-
else:在下一行 ->del link['href']和re.search('^.\B.\$xmastrees', link['href']) -
@Pedro Lobito return self.attrs[key] KeyError: 'href'
-
您需要this 吗?如果是这样,我会发布一个答案。
-
是的,这就是我要找的。span>
标签: python regex for-loop if-statement web-scraping