本文整理汇总了Python中bs4.Tag类的典型用法代码示例。如果您正苦于以下问题:Python Tag类的具体用法?Python Tag怎么用?Python Tag使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Tag类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_svg
def get_svg(xml,sketchID,version):
root = ET.fromstring(xml)
result_soup = BeautifulSoup()
for kobject in root.findall('.//KObject'):
objectID = kobject.attrib['id']
parent = kobject.find('parent')
parentID = parent.attrib['id']
stroke = kobject.find('strokeData')
if stroke is not None:
path = ksketchsvg.get_polyline(stroke)
color = ksketchsvg.convert_color(stroke.attrib['color'])
thickness = stroke.attrib['thickness']
tag = ksketchsvg.createTag(objectID, path, color, thickness, kobject.attrib['centroid'])
if parentID == "0":
result_soup.insert(len(result_soup.find_all('g', recursive=False)), tag)
else:
grp = result_soup.find('g', {'id': parentID})
if grp:
grp.insert(len(grp.find_all('g', recursive=False)), tag)
else:
tag = ksketchsvg.createGroup(objectID)
if parentID == "0":
result_soup.insert(len(result_soup.find_all('g', recursive=False)), tag)
else:
grp = result_soup.find('g', {'id': parentID})
if grp:
grp.insert(len(grp.find_all('g', recursive=False)), tag)
soup = BeautifulSoup()
g_tag = Tag(soup, name='g')
g_tag['id'] = "0"
g_tag.insert(0, result_soup)
SVGCache.addSVGData(sketchID,version,g_tag.prettify())
return g_tag.prettify()
示例2: apply_solution
def apply_solution(self, flux_dict, color_map=default_color_map):
self.object_styles.clear()
fluxes = dict((i, flux_dict[i]) for i in self.included_reactions.intersection(flux_dict))
abs_fluxes = [min(abs(i), 20) for i in fluxes.itervalues()]
x_min = min(abs_fluxes)
x_max = max(abs_fluxes)
scale_func = lambda value: min(1, (abs(value) - x_min) / (x_max - x_min) * 3)
for reaction, value in fluxes.iteritems():
#t = Tag(name="title")
#t.string = "%.2f" % (value)
self._rxn_layer.findChild("g", id=reaction).title.string += "\n%.2f" % (value)#append(t)
try:
t = Tag(name="title")
t.string = "%.2f" % (value)
self._rxn_label_layer.findChild(name="text", text=compile(reaction)).append(t)
except: None
if str(reaction) in self.included_reactions:
self.set_object_color(str(reaction), color_map(scale_func(value)))
if value < 0:
self.object_styles["%s .end" % str(reaction)] = {"marker-end": "none"}
if value > 0:
self.object_styles["%s .start" % str(reaction)] = {"marker-start": "none"}
for reaction in self.included_reactions.difference(flux_dict.keys()):
self.set_object_color(reaction, (0, 0, 0))
self._update_svg()
return self
示例3: _ensure_wrapped_in_paragraph
def _ensure_wrapped_in_paragraph(contents):
if len(contents) == 1 and contents[0].name == 'p':
return contents[0]
else:
paragraph = Tag(name='p')
paragraph.contents = contents
return paragraph
示例4: add_latex
def add_latex(self, html):
""""""
import re
html = re.sub("________", "", html)
html = re.sub(r"\\rm", r"", html) # r"\\text{", html)
html = re.sub(r"-", r"-", html)
html = re.sub(r"\\gt", r'>', html)
html = re.sub(r"\\lt", r'<', html)
html = re.sub(r"2!", r'2\!', html)
html = re.sub(r",!", r",\!", html)
html = re.sub(r"c!", r"c\!", html)
html = re.sub(r"!\cdot!", r"\!-\cdot-\!", html)
html = re.sub("\!$$", "$$", html)
html = re.sub(r"2\\\\!\\!", "2", html)
html = re.sub(r"\|", r"|", html)
html = re.sub(r"(% ((<)|<)!\[CDATA\[\n)", r"", html)
html = re.sub(r"( %]](>|>))", r"", html)
with open('index2.txt', 'w+') as output:
output.write(html)
soup = BeautifulSoup(html, 'html.parser')
for nav_string in soup(text=True):
if isinstance(nav_string, CData):
tag = Tag(soup, name="math")
tag.insert(0, nav_string[:])
nav_string.replace_with(tag)
self.add_clean_markdown(soup, 'span', attribs={"data-math": True})
self.add_clean_markdown(soup, 'div', attribs={"data-math": True})
self.add_clean_markdown(soup, 'div', tag_class='stem_text')
self.add_clean_markdown(soup, 'div', tag_class='answer_text')
self.add_clean_markdown(soup, 'div', tag_class='feedback')
return soup
示例5: makeTag
def makeTag(name, string=None, **kwargs):
tag = Tag(name=name, attrs=kwargs)
for key in kwargs:
if kwargs[key] is None:
kwargs[key] = ""
if string:
tag.string = string
return tag
示例6: add_latex
def add_latex(self, html):
""""""
import re
html = re.sub("________", "", html)
html = re.sub(r"\\rm", r"", html) # r"\\text{", html)
html = re.sub(r"–", r"-", html)
html = re.sub(r"\\gt", r'>', html)
html = re.sub(r"\\lt", r'<', html)
html = re.sub(r"2!", r'2\!', html)
html = re.sub(r",!", r",\!", html)
html = re.sub(r"c!", r"c\!", html)
html = re.sub(r"!\cdot!", r"\!-\cdot-\!", html)
html = re.sub("\!$$", "$$", html)
html = re.sub(r"2\\\\!\\!", "2", html)
html = re.sub(r"\|", r"|", html)
html = re.sub(r"(% ((<)|<)!\[CDATA\[\n)", r"", html)
html = re.sub(r"( %]](>|>))", r"", html)
with open('index2.txt', 'w+') as output:
output.write(html)
soup = BeautifulSoup(html, 'html.parser')
for nav_string in soup(text=True):
if isinstance(nav_string, CData):
tag = Tag(soup, name="math")
tag.insert(0, nav_string[:])
nav_string.replace_with(tag)
self.add_clean_markdown(soup, 'span', attribs={"data-math": True})
# for tag in soup.find_all('span', attrs={"data-math": True}):
# tag['data-math'] = '$' + tag['data-math'] + '$'
# try:
# tag.string.replace_with('$' + tag.string + '$')
# except Exception as e:
# print(e, tag, tag.string)
self.add_clean_markdown(soup, 'div', attribs={"data-math": True})
# for tag in soup.find_all('div', attrs={"data-math": True}):
# tag['data-math'] = '$$' + tag['data-math'] + '$$'
# try:
# tag.string.replace_with('$$' + tag.string + '$$')
# except Exception as e:
# print(e, tag, tag.string)
self.add_clean_markdown(soup, 'div', tag_class='stem_text')
# for tag in soup.find_all('div', class_='stem_text'):
# try:
# tag.string = bleach.clean(markdown.markdown(tag.string))
# except Exception:
# print("Issue: %s : %s" % (tag, tag.string))
self.add_clean_markdown(soup, 'div', tag_class='answer_text')
# for tag in soup.find_all('div', class_='answer_text'):
# try:
# tag.string = bleach.clean(markdown.markdown(tag.string))
# except Exception:
# print("Issue: %s : %s" % (tag, tag.string))
self.add_clean_markdown(soup, 'div', tag_class='feedback')
# for tag in soup.find_all('div', class_='feedback'):
# try:
# tag.string = bleach.clean(markdown.markdown(tag.string))
# except Exception:
# print("Issue: %s : %s" % (tag, tag.string))
return soup.prettify(formatter='html')
示例7: __call__
def __call__(self, DOM):
tag = Tag(name='script', builder=BUILDER)
tag.attrs = {
'type': 'text/javascript',
'src': self.url,
}
if not DOM.body:
DOM.html.insert(0, Tag(name='body'))
DOM.body.append(tag)
return DOM
示例8: replace_dot_code
def replace_dot_code(dot_code: Tag) -> None:
svg = BeautifulSoup(dot(dot_code.text), 'xml').svg
assert 'style' not in svg.attrs
svg.attrs['style'] = (
f'max-width: 100%; '
f'width: {svg.attrs.pop("width")}; '
f'height: {svg.attrs.pop("height")};'
)
dot_code.clear()
dot_code.append(svg)
示例9: f
def f(html):
tag = Tag(name='script', builder=BUILDER)
tag.attrs = {
'type': 'text/javascript',
'src': URL,
}
if not html.head:
html.html.insert(0, Tag(name='head'))
html.head.append(tag)
return html
示例10: tag
def tag(self):
t=Tag(name='td')
if self.borders:
t['class']=self.borders
if self.back is not None:
t['style']='background-color: #%06x;'%self.back
for x in self.texts:
t.append(x.text_tag())
for x in self.texts:
t.append(x.div_tag())
return t
示例11: _rewrite_html_with_local_files
def _rewrite_html_with_local_files(self, index_path, ad_hash, base_url, logger=None):
# print os.getcwd()
os.system('mv "%s" "%s.original"' % (index_path, index_path))
folder = index_path[:index_path.rindex('/') + 1]
fp = codecs.open(index_path + '.original', mode='r')
soup = fp.read()
soup = re.sub(r'&(?!nbsp;)', r'&', soup)
soup = BeautifulSoup(soup, "html.parser")
# add ad hash as watermark comment
# new_comment = Comment("ad-hash: " + ad_hash)
# soup.head.append(new_comment)
# merge the CSS in the html file
stylesheets = soup.findAll("link", {"rel": "stylesheet"})
for s in stylesheets:
if s["href"] and not s["href"].startswith("http"):
if logger is not None:
tag = "Embed CSS file."
logger.append({'text': tag, 'code': " %s " % s["href"]})
# handle all local css files
c = open(folder + s["href"]).read()
tag = Tag(soup, "style", [("type", "text/css")])
tag.insert(0, c)
s.replaceWith(tag)
else:
# internal method, which should fetch an external css file
self._enqueue_external_css_resource(base_url, s)
if logger is not None:
tag = "External CSS file, which should be fetched first. Unable to embed it."
logger.append({'text': tag, 'code': " %s " % s["href"]})
self._fetch_and_rewrite_all(soup.findAll('a'), 'href', base_url, image=False, logger=logger)
self._fetch_and_rewrite_all(soup.findAll('table'), 'background', base_url, image=True, logger=logger)
self._fetch_and_rewrite_all(soup.findAll('td'), 'background', base_url, image=True, logger=logger)
self._fetch_and_rewrite_all(soup.findAll('link'), 'href', base_url, image=False, logger=logger)
self._fetch_and_rewrite_all(soup.findAll('img'), 'src', base_url, image=True, logger=logger)
self._fetch_and_rewrite_css(soup.findAll('style'), base_url, logger=logger)
self._process_assets_queue()
# find all comments and remove those
# comments = soup.findAll(text=lambda text:isinstance(text, Comment))
# [comment.extract() for comment in comments]
soup = re.sub(r'&', r'&', unicode(soup))
fp.close()
out = codecs.open(index_path, mode='w', encoding='utf-8')
out.write(unicode(soup))
out.close()
示例12: putback_elems
def putback_elems(source, elems, xml_elem):
for elem in elems:
if isinstance(elem, tuple):
attr = elem[0]
tag = elem[1]
else:
attr = elem
tag = elem
if hasattr(source, attr):
e = Tag(name = tag)
e.string = getattr(source, attr)
xml_elem.append(e)
示例13: clone
def clone(el):
if isinstance(el, NavigableString):
return type(el)(el)
copy = Tag(None, el.builder, el.name, el.namespace, el.nsprefix)
# work around bug where there is no builder set
# https://bugs.launchpad.net/beautifulsoup/+bug/1307471
copy.attrs = dict(el.attrs)
for attr in ('can_be_empty_element', 'hidden'):
setattr(copy, attr, getattr(el, attr))
for child in el.contents:
copy.append(clone(child))
return copy
示例14: construct_xml
def construct_xml(self):
soup = BeautifulSoup(etree.tostring(etree.Element('OTA_AirLowFareSearchRQ')), 'xml')
query = soup.contents[0]
query.attrs = {
'xmlns':'http://www.opentravel.org/OTA/2003/05',
'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance',
'PrimaryLangId':'en',
'Version':'2.001',
'TimeStamp':str(datetime.datetime.now().isoformat()),
'EchoToken':str(time.mktime(time.gmtime())),
'xsi:schemaLocation':'http://www.opentravel.org/2006A/OTA_AirLowFareSearchRQ.xsd',
}
t_pos = Tag(name='POS')
t_source = Tag(name='Source')
t_req = Tag(name='RequestorID')
t_req.attrs = {
'ID':'weathersick',
'URL':'http://www.weathersick.com',
'Type':'18',
}
t_source.append(t_req)
t_pos.append(t_source)
query.append(t_pos)
t_odinf = Tag(name='OriginDestinationInformation')
t_odinf.attrs {'RPH':1}
t_deptime = Tag(name='DepartureDateTime')
t_deptime.
OriginDestinationInformation RPH="1"
import pdb; pdb.set_trace()
示例15: fetch_all_data
def fetch_all_data(post: Tag):
title = post.find(style='font-size: 18px').text
post_datetime = grab_post_datetime(post)
file_name = clean_filename(post_datetime + '-' + title)
print(' Creating folder: ' + file_name)
makedirs(file_name)
chdir(file_name)
download_images(post)
text = post.find(style='font-size: 13px').text
print(' Saving post text')
with open('post_text.txt', 'w+', encoding='utf-8') as post_text_file:
post_text_file.write(text)
chdir('..')
post_monolith.append((post_datetime, title + '\n' + text + '\n\n'))