【发布时间】:2018-04-16 14:55:40
【问题描述】:
我编写了一个脚本来解析每个网页的可见文本contact 或about 中的可用链接。然而,当我运行我的脚本时,我可以看到我的爬虫总是用于解析about 中的链接。只有当about 不可用时,它才会解析contact 中的链接。我怎样才能让我的脚本做相反的事情,我的意思是它会寻找连接到contact而不是about的链接。如果contact 不可用,那么只有它会解析about。我尝试了以下方法来完成它,但它正在按照我描述的方式进行。
这是我的尝试:
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup
links = (
"http://www.mount-zion.biz/",
"http://www.latamcham.org/",
"http://www.innovaprint.com.sg/",
"http://www.cityscape.com.sg/"
)
def Get_Link(site):
res = requests.get(site)
soup = BeautifulSoup(res.text,"lxml")
for item in soup.select("a[href]"):
if "contact" in item.text.lower():
abslink = urljoin(site,item['href']) ##I thought the script prioritizes the first condition but I am wrong
print(abslink)
break
else:
if "about" in item.text.lower():
abslink = urljoin(site,item['href'])
print(abslink)
break
if __name__ == '__main__':
for link in links:
Get_Link(link)
有没有办法根据条件的可用性来确定条件的优先级?
底线是我想让链接连接到contact。如果它不可用,则脚本将查找连接到about 的链接。
【问题讨论】:
-
考虑到多个
if's和elif's语句之间的差异,您将此标记为重复,而我的问题是优先于另一个@jpp。我的帖子是用希伯来语写的吗? -
不,但如果你这样做,我可能会更好地理解你!
标签: python python-3.x if-statement web-scraping