Python requests+bs4 爬取TCMSP的资源获得清肺排毒汤的靶向基因
为研究清肺排毒汤的中药材对于新冠肺炎的作用机制,需要收集相关数据,于是将目光洒向了TCMSP。。
检索首页是这样的:
接下来用一味药材进行检索。
中药材检索界面获取
以清肺排毒汤中的麻黄为例,进行检索后它的界面是这样的,注意观察url:
http://tcmspw.com/tcmspsearch.php?qs=herb_all_name&q=麻黄&token=9b8fe8d60b5028b2eb0ee7e5e7834a40
找规律:
1.http://tcmspw.com/tcmspsearch.php?qs=herb_all_name&q=麻黄&token=9b8fe8d60b5028b2eb0ee7e5e7834a40
也可能是这样:
http://tcmspw.com/tcmspsearch.php?qs=herb_all_name&q=%E9%BA%BB%E9%BB%84&token=9b8fe8d60b5028b2eb0ee7e5e7834a40
2.http://tcmspw.com/tcmspsearch.php?qs=herb_all_name&q=广藿香&token=9b8fe8d60b5028b2eb0ee7e5e7834a40
也可能是这样:
http://tcmspw.com/tcmspsearch.php?qs=herb_all_name&q=%E5%B9%BF%E8%97%BF%E9%A6%99&token=9b8fe8d60b5028b2eb0ee7e5e7834a40
也就是说url可能对中文字符进行了16进制的编码。
发现除了q=后面的中药材名称不同,其他的都相同,而且可以分为四大块:
1.http://tcmspw.com/tcmspsearch.php?
2.qs=herb_all_name&q=
3.中药名或者其对应的16进制的编码
4.&token=9b8fe8d60b5028b2eb0ee7e5e7834a40
然后可以写代码了:
导入需要的库,parse是用以解码中文的。当用中文访问失败时,可以将中文解码再试试。后面解码的过程注释掉了。
import requests
# import urllib.parse # urllib用以解码中药材名称,是否需要见具体需求
from bs4 import BeautifulSoup
import re
import xlsxwriter
class get_drug_target(object):
def __init__(self):
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36',
}
self.base_url = 'http://tcmspw.com/tcmspsearch.php?'
根据上面提到的格式将url进行拼接,并请求:
def get_url(self, drug):
# 下面注释的是中文解码的过程
# drug_decode = urllib.parse.quote(drug)
# url = self.base_url+'qs=herb_all_name&q='+drug_decode+'&token=f8abf58ec1d6b214e0d6ca4ec94ee7d3'
# 下面是不解码
url = self.base_url+